python:类的魔术方法-magic method

引入

类的魔术方法是什么:定义在类里的特殊方法,一般格式为__func__

有什么用:方便的实现各种特定的功能。

下面简单汇总下各种魔术方法,以后方便自己查阅。

魔术方法汇总

根据不同的功能,将其简单分为几类。

构造和初始化

方法 功能
__new__ (cls,other) 创建类并返回这个类的实例
__init__(self, other) 根据传入参数初始化实例。注意与__new__的区别:实际在构造实例时,会先执行__new__创建并返回这个实例,然后再初始化属性。两者共同组成一个“构造函数”
__del__(self) 析构函数,再对象生命周期结束时调用

获取类的信息

方法 功能
__doc__(self) 返回定义类时标注的字符串,默认是None
__str__(self) str()
print实例时打印出来的内容
__repr__(self) repr()
__dir__(self) dir()
返回所有的属性和方法
__dict__(self) 类调用:返回这个类中已经定义了的属性和方法
实例调用:返回属性的字典
__module__(self) 返回类所在的模块
__class__(self) 实例调用,表明实例属于哪个类

属性访问控制

方法 功能
__getattr__(self, name) 定义了你试图访问一个不存在的属性时的行为
__setattr__(self, name,value) 定义了你对属性进行赋值和修改操作时的行为
__delattr__(self, name) 定义的是你删除属性时的行为
__getattribute__(self, name) 定义了你的属性被访问时的行为

重载运算符

算数运算符

方法 功能
__add__(self, other) +
__sub__(self, other) -
__mul__(self, other) *
__div__(self, other) /
__floatdiv__(self, other) //
__mod__(self, other) %
__pow__(self, other) **

比较运算符

方法 功能
__lt__(self, other) <
__gt__(self, other) >
__le__(self, other) <=
__ge__(self, other) >=
__eq__(self, other) ==
__ne__(self, other) !=

位运算符

方法 功能
__lshift__(self, other) <<
__rshift__(self, other) >>
__and__(self, other) &
__or__(self, other) |
__xor__(self, other) ^

注意:若对布尔变量(True,False)进行位运算,其等价于逻辑运算符。

赋值运算符

方法 功能
__iadd__(self, other) +=
__isub__(self, other) -=
__imul__(self, other) *=
__idiv__(self, other) /=
__ifloatdiv__(self, other) //=
__imod__(self, other) %=
__ipow__(self, other) **=

Unary Operators

方法 功能
__neg__(self) -
__pos__(self) +
__abs__(self) abs()
__invert__(self) ~
__round__(self) round()
__floor__(self) floor()
__ceil__(self) ceil()

类型转换

方法 功能
__complex__(self) complex()
__int__(self) int()
__long__(self) long()
__float__(self) float()
__oct__(self) oct()
__hex__(self) hex()

其他

方法 功能
__call__(self, *args) 实现该方法后,可像函数一样直接调用实例。比如obj()

未完待续…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章