增量赋值运算的相关魔法方法
方法 | 作用 |
---|---|
iadd(self,other) | 定义赋值加法的行为 |
isub(self,other) | 定义赋值减法的行为 |
imul(self,other) | 定义赋值乘法的行为 |
itruediv(self,other) | 定义赋值真除法的行为 |
ifloordiv(self,other) | 定义赋值整数除法的行为 |
imod(self,other) | 定义赋值取模算法的行为 |
idivmod(self,other) | 定义赋值取余算法的行为(a\\b余数) |
ipow(self,other) | 定义当赋值幂运算**运算时的行为 |
ilshift(self,other) | 定义赋值按位左移位的行为 |
irshift(self,other) | 定义赋值按位右移位的行为 |
iand(other) | 定义赋值按位与操作的行为& |
ixor(self,other) | 定义赋值按位异或操作的行为:^ |
ior(self,other) | 定义赋值按位或操作的行为 |
反运算的相关魔法方法
方法 | 作用 |
---|---|
radd(self,other) | 定义加法的行为(当左操作数不支持相应的操作是被调用) |
rsub(self,other) | 定义减法的行为(当左操作数不支持相应的操作是被调用) |
rmul(self,other) | 定义乘法的行为(当左操作数不支持相应的操作是被调用) |
rtruediv(self,other) | 定义真除法的行为(当左操作数不支持相应的操作是被调用) |
rfloordiv(self,other) | 定义整数除法的行为(当左操作数不支持相应的操作是被调用) |
rmod(self,other) | 定义取模算法的行为(当左操作数不支持相应的操作是被调用) |
rdivmod(self,other) | 定义当divmod()调用时的行为(a\\b余数)(当左操作数不支持相应的操作是被调用) |
rpow(self,other) | 定义当被power()调用或**运算时的行为(当左操作数不支持相应的操作是被调用) |
rlshift(self,other) | 定义按位左移位的行为(当左操作数不支持相应的操作是被调用) |
rrshift(self,other) | 定义按位右移位的行为(当左操作数不支持相应的操作是被调用) |
rand(other) | 定义按位与操作的行为&(当左操作数不支持相应的操作是被调用) |
rxor(self,other) | 定义按位异或操作的行为:^(当左操作数不支持相应的操作是被调用) |
ror(self,other) | 定义按位或操作的行为(当左操作数不支持相应的操作是被调用) |
下面通过几个例子来熟悉一下python的这些魔法方法:
>>> class A(int):
def __radd__(self,other):
print('__radd__被调用了')
return int.__add__(self,other)
>>> a=A(6)
>>> b=A(9)
>>> a+b
15
>>> 2+b
__radd__被调用了
11
>>> class A(int):
def __radd__(self,other):
print('__radd__被调用了')
return int.__rsub__(other,self)#这里self和other的位置替换了
>>> b=A(9)
>>> 2+b
__radd__被调用了
7
定义一个类,当实例化该类是,自动判断传入了多少个参数,并显示出来。
>>> class B:
def __init__(self,*args):#这里*表示传递多类参数,若不加*默认这里只有两个位置,而输入的占四个位置,从而出现错误,self也占一个位置
if not args:
print('没有传入参数')
else:
print('传入了%d个参数,分别是:'%len(args),end='')
for each in args:
print(each,end='、')
>>> b=B(2,6,8)
传入了3个参数,分别是:2、6、8、