5_Python OOP

时间:2023-03-09 16:04:05
5_Python OOP

1. 实例属性和类属性

       (1) 实例属性在构造函数__init__中定义,定义时以self作为前缀,只能通过实例名访问

       (2) 类属性在类中方法之外单独定义,还可以在程序中通过类名增加,建议通过类名直接访问。

class Product:							##建议首字母大写
price = 100 ##类属性
def __init__(self,c):
self.color = c ##实例属性 ##主程序
Product1 = Product("red")
Product2 = Product("yellow") Product.price = 120 ##修改类属性值
Product.name = "shoes" ##增加类属性 Product1.color = "black" ##修改实例属性

       (3) 私有属性以__开头,否则是公有属性。私有属性在类外不能直接访问。而是通过特殊方式访问私有属性:

class Food:
def __init__(self):
self.__color = 'red' ##私有属性定义格式
self.price = 0 ##主程序
>>>apple = Food()
>>>apple.(_)Food__color = "blue" ##私有属性修改格式
>>>print(apple._Food__color) ##私有属性访问格式 blue


2. 类的方法

class Fruit:
price = 0 ##类属性 def __init__(self):
self.__color = 'red' ##私有属性 def __outputColor(self): ##私有方法
print(self.__color) def output(self): ##公有方法
self.__outputColor() @staticmethod ##静态方法
def getprice():
return Fruit.frice @classmethod ##类方法
def fget(cls):
print(cls)


3. 构造函数和析构函数

def __init__(self,first = '',last = '',id = 0):
self.firstname = first
self.lastname = last
self.idint = id def __del__(self):
print("self was dead")


4. 常用的运算符重载

方法 重载 调用
__add__ + x+y
__or__ | x|y
__repr__ 打印 repr(x)
__str__ 转换 str(x)
__call__ 函数调用 x(*args,**key)
__getattr__ 点号运算 x.undefine
__setattr__ 属性赋值 x.any=value
__delattr__ 属性删除 del x.any
__getattribute__ 属性获取 x.any
__getitem__ [] x[key]
__setitem__ 索引赋值 x[key]=value
__delitem__ 索引删除 del x[key]
__len__ 长度 len(x)
__bool__ 布尔测试 bool(x)
__lt__,__gt__ 小于,大于
__le__,__ge__ 小于等于,大于等于
__eq__,__ne__ 等于,不等于
__contain__ in item in x
__iter__,__next__ 迭代 I=iter(x),next(x)


5. 继承

        与C++继承实现类似

class sub(super):
def __init__(self):