python魔法方法

python3中比较重要魔法方法

初始化和构造方法 描述
__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.

你可能感兴趣的:(python)