参考 docs.python.org 基于python 2.7.5
http://www.rafekettler.com/magicmethods.html
(a) object.__new__(class[,...])
作用:创建一个新的instance;如果__new__()返回了一个(参数)类的instance,则会执行__init()__,而如果没有返回,则__init__()不会执行。__new__()不常用,主要用于子类来自定义instance的创建等
(b) object.__init__(self[,...])
作用:当instance创建时执行__init__的内容。类似类的初始化,十分常见
作用:当instance需要被删除时执行,解构器的功能。尽量避免使用。
这里是一个使用__init__和__del__的例子
(a) object.__lt__(self, other)、__le__(self,other)、__eq__(self, other)、__ne__(self, other)、__gt__(self, other)、__ge__(self, other)
作用:x<y => x.__lt__(y) 以此类推
(b) object.__cmp__(self, other)
如果2(a)没有定义,则比较时会执行__cmp__,如果self < other返回负整数,相等则返回0,大于则返回正整数
(a) object.__hash__(self)
hash()执行此操作,返回整数;如果类没有定义__cmp__()或者__eq__(),则也不应该定义__hash__();例如用于字典中用于快速key对比
(b) object.__str__(self), object.__repr__(self)
定义str()和repr()的行为,前者不一定为有效的python表达式,后者需要为有效的python表达式
(c) object.__unicode__(self)
定义unicode()的行为,返回unicode对象。如果此方法未被定义而执行了字符转换的话,系统会用默认设定来进行编码
(d) object.__nonzero__(self)
定义真值测试以及bool()的行为,范围True/False,或者0/1
object.__add__(self, other)
object.__sub__(self, other)
object.__mul__(self, other)
object.__floordiv__(self, other)
object.__mod__(self, other)
object.__divmod__(self, other)
object.__pow__(self, other[, modulo])
object.__lshift__(self, other)
object.__rshift__(self, other)
object.__and__(self, other)
object.__xor__(self, other)
object.__or__(self, other)
object.__div__(self, other)
object.__truediv__(self, other)
object.__radd__(self, other)
object.__rsub__(self, other)
object.__rmul__(self, other)
object.__rdiv__(self, other)
object.__rtruediv__(self, other)
object.__rfloordiv__(self, other)
object.__rmod__(self, other)
object.__rdivmod__(self, other)
object.__rpow__(self, other)
object.__rlshift__(self, other)
object.__rrshift__(self, other)
object.__rand__(self, other)
object.__rxor__(self, other)
object.__ror__(self, other)
object.__iadd__(self, other)
object.__isub__(self, other)
object.__imul__(self, other)
object.__idiv__(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.__coerce__(self, other)