(其他python纪要,请参考:
1. __new__(cls[, ...])2. __init__(self[, ...])super().__init__([args...])。举例:>>> class Rect():... def __init__(self, x, y):... self.x = x... self.y = y... def getArea(self):... return self.x *self.y... >>> r1= Rect(3,4)>>> r1.getArea()123. __del__(self)del__()方法,子类中进行了重写,此时若要调用父类中的__del__(),则必须显式调用,形如:super().__del__()。当对象有多个变量名指向时,仅当最后一个变量名被del时,才会调用__del__()。举例:>>> class Test():... def __del__(self):... print('__del__() is called')... >>> a = Test()>>> b = a>>> del a>>> del b__del__() is called十四、算术运算、反运算、增量赋值运算符、一元运算符通过Python下列魔法方法,可实现自定义对象的数值运算。下述方法可重新定制以下算术运算:(+, -, *, @, /, //, %, divmod(),pow(), **, <<, >>, &, ^, |)

object.__iadd__(self, other) +=object.__isub__(self, other) -=object.__imul__(self, other) *=object.__imatmul__(self, other) @=object.__itruediv__(self, other) /=object.__ifloordiv__(self, other) //=object.__imod__(self, other) %=object.__ipow__(self, other[, modulo]) **=object.__ilshift__(self, other) <<=object.__irshift__(self, other) >>=object.__iand__(self, other) &=object.__ixor__(self, other) ^=object.__ior__(self, other) |=
object.__neg__(self) +object.__pos__(self) -object.__abs__(self) abs()object.__invert__(self) ~
表现类魔法方法包括:__repr__(self) 、__str__(self),其各自用途略微不同。print()打印操作会首先尝试__str__和str内置函数(print运行的内部等价形式),仅当__str__()未定义而__repr__()定义的情况下,返回__repr__()的结果。__repr__()用于所有其他的环境中:用于交互模式下提示回应以及repr函数。它通常应该返回一个编码字符串,可以用来重新创建对象,或者给开发者详细的显示。object.__lt__(self, other) <object.__le__(self, other) <=object.__eq__(self, other) ==object.__ne__(self, other) !=object.__gt__(self, other) >object.__ge__(self, other) >=
__getattr__(self, name) 当用户试图获取一个不存在的属性时的行为__getattribute__(self, name) 当对象的属性被访问时的行为__setattr__(self, name, value)当对象的属性被设置时的行为__delattr__(self, name) 当对象的属性被删除时的行为__get__(self, instance, owner) 用于访问属性,返回属性值
__set__(self, instance, value) 将在属性分配操作中调用,不返回任何值
__del__(self, instance) 控制删除操作,不返回任何值
其中:self是描述符类自身的实例
instance是描述符的拥有者所在的类的实例
owner是描述符的拥有者所在的类本身
描述符是对多数属性运用相同存取方式的一种技巧。单独的描述符没有什么意义,只有描述符实例托管在另一个类(以后统称托管类)中作为类属性才有意义。举例:
>>> class Desc(object):
... def __init__(self,name):
... self.name = name
... def __get__(self, instance, owner):
... print("call __get__ , name=", self.name)
...
>>> class TestDesc(object):
... x = Desc('x')
... def __init__(self, x, y):
... self.y = Desc('y')
...
>>> t = TestDesc()
>>> t.x
call __get__ , name= x
>>> t.y
<__main__.Desc object at 0x7f5da9bba908>
说明:
1)t.x访问Owner的 __getattribute__() 方法(即:TestDesc.__getattribute__()),发现t没有实例属性x,然后访问类TestDesc,发现类属性x。python判断该类属性x为描述符,因此依据描述符协议,将 TestDesc.x 转化为 TestDesc.__dict__['x'].__get__(None, TestDesc) 来访问,并进入类Desc的 __get__()方法,进行相应的操作。
2)t.y访问Owner的 __getattribute__() 方法,该方法将 t.y 转化为TestDesc.__dict__['y'].__get__(t, TestDesc), 但是呢,实际上 TestDesc 并没有 y这个属性,y 是属于实例对象的,因此只能忽略了。

评论
本人一定要到专页加个关注
我一定分享
LZ实在最棒
本人不得不安利