初始化和构造方法 | 描述 |
---|---|
__ new__ (cls, other) |
对象实例化时调用. |
__ init__ (self, other) |
被__new__ 方法调用 |
__ del__ (self) |
析构函数 |
__new__
(cls, […)
__new__
是用来创建类并返回这个类的实例, 而__init__
只是将传入的参数来初始化该实例.
__new__
在创建一个实例的过程中必定会被调用,但__init__
就不一定
__init__
(self, […)
对象初始化的时候调用,
__del__
(self)
在对象的生命周期结束时, __del__
会被调用,可以将__del__
理解为"析构函数".
__del__
定义的是当一个对象进行垃圾回收时候的行为。
有一点容易被人误解, 实际上,x.__del__
() 并不是对于del x的实现,但是往往执行del x时会调用x.__del__
().
一元运算符和函数 | 描述 |
---|---|
__ pos__ (self) |
To get called for unary positive e.g. +someobject. |
__ neg__ (self) |
To get called for unary negative e.g. -someobject. |
__ abs__ (self) |
To get called by built-in abs() function. |
__ invert__ (self) |
To get called for inversion using the ~ operator. |
__ round__ (self,n) |
To get called by built-in round() function. |
__ floor__ (self) |
To get called by built-in math.floor() function. |
__ ceil__ (self) |
To get called by built-in math.ceil() function. |
__ trunc__ (self) |
To get called by built-in math.trunc() function. |
类型转换 | 描述 |
---|---|
__ int__ (self) |
To get called by built-int int() method to convert a type to an int. |
__ float__ (self) |
To get called by built-int float() method to convert a type to float. |
__ complex__ (self) |
To get called by built-int complex() method to convert a type to complex. |
__ oct__ (self) |
To get called by built-int oct() method to convert a type to octal. |
__ hex__ (self) |
To get called by built-int hex() method to convert a type to hexadecimal. |
__ index__ (self) |
To get called on type conversion to an int when the object is used in a slice expression. |
__ trunc__ (self) |
To get called from math.trunc() method. |
字符串操作魔法方法 | 描述 |
---|---|
__ str__ (self) |
To get called by built-int str() method to return a string representation of a type. |
__ repr__ (self) |
To get called by built-int repr() method to return a machine readable representation of a type. |
__ format__ (self, formatstr) |
To get called by built-int string.format() method to return a new style of string. |
__ hash__ (self) |
To get called by built-int hash() method to return an integer. |
__ nonzero__ (self) |
To get called by built-int bool() method to return True or False. |
__ dir__ (self) |
To get called by built-int dir() method to return a list of attributes of a class. |
__ sizeof__ (self) |
To get called by built-int sys.getsizeof() method to return the size of an object. |
对象魔法方法 | 描述 |
---|---|
__ getattr__ (self, name) |
Is called when the accessing attribute of a class that does not exist. |
__ setattr__ (self, name, value) |
Is called when assigning a value to the attribute of a class. |
__ delattr__ (self, name) |
Is called when deleting an attribute of a class. |
__getattr__
(self, name)
该方法定义了你试图访问一个不存在的属性时的行为。因此,重载该方法可以实现捕获错误拼写然后进行重定向, 或者对一些废弃的属性进行警告。
__setattr__
(self, name, value)
__setattr__
是实现封装的解决方案,它定义了你对属性进行赋值和修改操作时的行为。
不管对象的某个属性是否存在,它都允许你为该属性进行赋值,因此你可以为属性的值进行自定义操作。有一点需要注意,实现__setattr__
时要避免"无限递归"的错误,下面的代码示例中会提到。
__delattr__
(self, name)
__delattr__
与__setattr__
很像,只是它定义的是你删除属性时的行为。实现__delattr__
是同时要避免"无限递归"的错误。
__getattribute__
(self, name)
__getattribute__
定义了你的属性被访问时的行为,相比较,__getattr__
只有该属性不存在时才会起作用。
因此,在支持__getattribute__
的Python版本,调用__getattr__
前必定会调用 __getattribute__
。__getattribute__
同样要避免"无限递归"的错误。
需要提醒的是,最好不要尝试去实现__getattribute__
,因为很少见到这种做法,而且很容易出bug。
例子说明__setattr__
的无限递归错误:
def__setattr__(self, name, value):
self.name = value
# 每一次属性赋值时, __setattr__都会被调用,因此不断调用自身导致无限递归了。
因此正确的写法应该是:
def__setattr__(self, name, value):
self.__dict__[name] = value
__delattr__
如果在其实现中出现del self.name
这样的代码也会出现"无限递归"错误,这是一样的原因。
下面的例子很好的说明了上面介绍的4个魔术方法的调用情况:
classAccess(object):
def__getattr__(self, name):
print '__getattr__'
return super(Access, self).__getattr__(name)
def__setattr__(self, name, value):
print '__setattr__'
return super(Access, self).__setattr__(name, value)
def__delattr__(self, name):
print '__delattr__'
return super(Access, self).__delattr__(name)
def__getattribute__(self, name):
print '__getattribute__'
return super(Access, self).__getattribute__(name)
access = Access()
access.attr1 = True # __setattr__调用
access.attr1 # 属性存在,只有__getattribute__调用
try:
access.attr2 # 属性不存在, 先调用__getattribute__, 后调用__getattr__
except AttributeError:
pass
del access.attr1 # __delattr__调用
运算魔法方法 | 描述 |
---|---|
__ add__ (self, other) |
To get called on add operation using + operator |
__ sub__ (self, other) |
To get called on subtraction operation using - operator. |
__ mul__ (self, other) |
To get called on multiplication operation using * operator. |
__ floordiv__ (self, other) |
To get called on floor division operation using // operator. |
__ div__ (self, other) |
To get called on division operation using / operator. |
__ mod__ (self, other) |
To get called on modulo operation using % operator. |
__ pow__ (self, other[, modulo]) |
To get called on calculating the power using ** operator. |
__ lt__ (self, other) |
To get called on comparison using < operator. |
__ le__ (self, other) |
To get called on comparison using <= operator. |
__ eq__ (self, other) |
To get called on comparison using == operator. |
__ ne__ (self, other) |
To get called on comparison using != operator. |
__ gt__ (self, other) |
To get called on comparison using > operator. |
__ ge__ (self, other) |
To get called on comparison using >= operator. |