我们知道语句:
a = int(‘3’)
b = int('2')
是将类int实例化的过程.
这在本人介绍工厂函数的博客中有过介绍
当python遇到“+”号时,会自动调用__add__方法。
class Nint(int):
def __add__(self,other):
return int(self)+int(other)
在这里前面的实例:a是self,b是other。
如果在实例:a中找不到__add__方法,那么会自动调用b中的__radd__方法
class Nint(int):
def __radd__(self,other):
rethrn int(self)+int(other)
这时,b是self,而a为other。(因为__radd__是实例b的方法)
例如:
>>> 1+b # 数字1找不到__add__,则自动调用b中的__radd__
>>> 3 # 实际执行的是:b+1
注意:1+b与b+1顺序并不相同。
如果是减号、除号,则计算结果也会不同
魔法方法中的运算方法与反运算方法:
运算方法 | 当遇到该符号调用 |
---|---|
add(self, other) | + |
sub(self, other) | - |
mul(self, other) | * |
truediv(self, other) | / |
floordiv(self, other) | // |
mod(self, other) | % |
divmod(self, other) | 当被 divmod() 调用时的行为 |
pow(self, other[, modulo]) | 当被 power() 调用或 ** 运算时的行为 |
lshift(self, other) | 左移位:<< |
rshift(self, other) | 右移位:>> |
and(self, other) | & |
xor(self, other) | 异或运算:^ |
or(self, other) | 或: |
反运算:(与上方相同,当左操作数不支持相应的操作时被调用)
在名字在前面加上r即可:
radd(self, other)