在Python中,所有以“__”双下划线包起来的方法,都统称为“Magic Method”(魔术方法)。
常用的魔术方法详解:
1__init__:构造器,当一个实例被创建的时候调用的初始化方法
class Test:
def __init__(self):
print("__init__方法")
Test()
__init__方法
2__new__:在对象初始化之前调用的第一个方法
默认调用object类里面的__new__方法。如果重写new方法要调用父类里面的new方法,将对象返回,常用的场景是实现单例模式。
class Test:
def __init__(self):
print("__init__方法")
def __new__(cls, *args, **kwargs):
print("重写new方法")
return super().__new__(cls)
m = Test()
>>>>重写new方法
>>>>__init__方法
3__call__: 允许一个类的实例像函数一样被调用:x(a, b) 调用 x.call(a, b)
class Test:
def __call__(self, *args, **kwargs):
print("-----call------")
t = Test()
t()
>>>> -----call------
4__del__(self) :析构器,当一个实例被销毁的时候调用的方法,非手动调用时会在程序最后触发__del__,而手动调用del时则会触发__del__,并不是程序最后。
class Test:
def __init__(self, name):
self.name = name
def __del__(self):
print("触发__del__")
t = Test("python")
print("end")
>>>>end
>>>>触发__del__
del t
print("end")
>>>>触发__del__
>>>>end
5__len__(self): 定义当被 len() 调用时的行为,使len函数可以直接检测对象中某个数据的长度
class Test:
def __init__(self, name):
self.name = name
def __len__(self):
return len(self.name) # 必须有返回值,且必须为int类型
t = Test("mingming")
print(len(t))
>>>>8
6__str__(self):定义当被 str() 调用时的行为,可以自定义打印对象时输出内容
class Test:
def __init__(self, name):
self.name = name
def __str__(self):
return "hello world" #必须有返回值,且必须为str类型
t = Test("mingming")
print(t)
>>>>hello world
7__bool__(self): 定义当被 bool() 调用时的行为,返回 True 或 False
class Test:
def __init__(self, name):
self.name = name
def __bool__(self):
if self.name =="python": # 返回对象必须是True 或 False
return True
else:
return False
t = Test("python")
t1 = Test("java")
print(bool(t))
print(bool(t1))
>>>>True
>>>>False
8__getattribute__(self, name):定义当该类的属性被访问时的行为,查找属性时第一时间进入该方法中
class Test:
def __getattribute__(self, item):
return "test"
t = Test()
print(t.name)
>>>>test
9__getattr__(self, name):定义当用户试图获取一个不存在的属性时的行为,找不到属性时会触发AttributeError异常并调用该方法。
class Test(object):
def __getattribute__(self, item):
print("首先进入该方法")
super().__getattribute__(item)
def __getattr__(self, item):
return "没有找到属性"
t = Test()
print(t.name)
>>>>首先进入该方法
>>>>没有找到属性
10__setattr__(self, name, value):属性被设置时的行为,设置属性时会进入到该方法中
class Test(object):
def __setattr__(self, key, value):
print("设置属性")
super().__setattr__(key,value) # 调用父类设置属性的方法
t = Test()
t.name = "python"
print(t.name)
>>>>设置属性
>>>>python
11__delattr__(self, name):定义当一个属性被删除时的行为
class Test(object):
def __init__(self, name):
self.name = name
def __delattr__(self, item):
print("删除属性")
super().__delattr__(item)
t = Test("python")
del t.name
print(t.__dict__)
>>>>删除属性
>>>>{}
12__repr__(self):定义当被 repr() 调用时的行为
13__hash__(self):定义当被 hash() 调用时的行为
14__format__(self, format_spec):定义当被 format() 调用时的行为有关属性
15__bytes__(self) :定义当被 bytes() 调用时的行为
16__dir__(self):定义当 dir() 被调用时的行为
17__get__(self, instance, owner):定义当描述符的值被取得时的行为
18__set__(self, instance, value) :定义当描述符的值被改变时的行为
19__delete__(self, instance):定义当描述符的值被删除时的行为
比较操作符
1__lt__(self, other):定义小于号的行为:x < y 调用 x__lt__(y)
2__le__(self, other) :定义小于等于号的行为:x <= y 调用 x__le__(y)
3__eq__(self, other):定义等于号的行为:x == y 调用 x__eq__(y)
4__ne__(self, other):定义不等号的行为:x != y 调用 x__ne__(y)
5__gt__(self, other) :定义大于号的行为:x > y 调用 x__gt__(y)
6__ge__(self, other):定义大于等于号的行为:x >= y 调用x__ge__(y)
算数运算符
1__add__(self, other):定义加法的行为:+
2__sub__(self, other):定义减法的行为:-
3__mul__(self, other):定义乘法的行为:*
4__truediv__(self, other):定义真除法的行为:/
5__floordiv__(self, other):定义整数除法的行为://
6__mod__(self, other):定义取模算法的行为:%
7__divmod__(self, other):定义当被 divmod() 调用时的行为
8__pow__(self, other[, modulo]):定义当被 power() 调用或 ** 运算时的行为
9__lshift__(self, other):定义按位左移位的行为:<<
10__rshift__(self, other):定义按位右移位的行为:>>
11__and__(self, other):定义按位与操作的行为:&
12__xor__(self, other) :定义按位异或操作的行为:^
13__or__(self, other):定义按位或操作的行为:|
反运算
1__radd__(self, other) :(与上方相同,当左操作数不支持相应的操作时被调用)
2__rsub__(self, other) :与上方相同,当左操作数不支持相应的操作时被调用)
3__rmul__(self, other) :(与上方相同,当左操作数不支持相应的操作时被调用)
4__rtruediv__(self, other):(与上方相同,当左操作数不支持相应的操作时被调用)
5__rfloordiv__(self, other):(与上方相同,当左操作数不支持相应的操作时被调用)
6__rmod__(self, other):(与上方相同,当左操作数不支持相应的操作时被调用)
7__rdivmod__(self, other):(与上方相同,当左操作数不支持相应的操作时被调用)
8__rpow__(self, other):(与上方相同,当左操作数不支持相应的操作时被调用)
9__rlshift__(self, other):(与上方相同,当左操作数不支持相应的操作时被调用)
10__rrshift__(self, other) :(与上方相同,当左操作数不支持相应的操作时被调用)
11__rand__(self, other):(与上方相同,当左操作数不支持相应的操作时被调用)
12__rxor__(self, other):(与上方相同,当左操作数不支持相应的操作时被调用)
13__ror__(self, other):(与上方相同,当左操作数不支持相应的操作时被调用)
增量赋值运算
1__iadd__(self, other): 定义赋值加法的行为:+=
2__isub__(self, other): 定义赋值减法的行为:-=
3__imul__(self, other) :定义赋值乘法的行为:*=
4__itruediv__(self, other):定义赋值真除法的行为:/=
5__ifloordiv__(self, other):定义赋值整数除法的行为://=
6__imod__(self, other):定义赋值取模算法的行为:%=
7__ipow__(self, other[, modulo]) :定义赋值幂运算的行为:**=
8__ilshift__(self, other):定义赋值按位左移位的行为:<<=
9__irshift__(self, other):定义赋值按位右移位的行为:>>=
10__iand__(self, other):定义赋值按位与操作的行为:&=
11__ixor__(self, other):定义赋值按位异或操作的行为:^=
12__ior__(self, other):定义赋值按位或操作的行为:|=
一元操作符
13__pos__(self):定义正号的行为:+x
14__neg__(self):定义负号的行为:-x
15__abs__(self):定义当被 abs() 调用时的行为
16__invert__(self):定义按位求反的行为:~x
类型转换
17__complex__(self):定义当被 complex() 调用时的行为(需要返回恰当的值)
18__int__(self):定义当被 int() 调用时的行为(需要返回恰当的值)
19__float__(self) :定义当被 float() 调用时的行为(需要返回恰当的值)
20__round__(self[, n]) :定义当被 round() 调用时的行为(需要返回恰当的值)
21__index__(self): 当对象是被应用在切片表达式中时,实现整形强制转换如果你定义了一个可能在切片时用到的定制的数值型,你应该定义 __index__如果 index 被定义,则 __int__也需要被定义,且返回相同的值
容器类型
1__getitem__(self, key):定义获取容器中指定元素的行为,相当于 self[key]
2__setitem__(self, key, value):定义设置容器中指定元素的行为,相当于 self[key] = value
3__delitem__(self, key):定义删除容器中指定元素的行为,相当于 del self[key]
4__iter__(self):定义当迭代容器中的元素的行为
5__reversed__(self):定义当被 reversed() 调用时的行为
6__contains__(self, item):定义当使用成员测试运算符(in 或 not in)时的行为