|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
class New_int(int):
def __add__(self, other):
return int.__sub__(self, other)
def __sub__(self, other):
return int.__add__(self, other)
a = New_int(6)
b = New_int(5)
c = b + a
print(c) # -1
使用同一个类,a的值是6,b的值是5,为什么相加的结果是-1?
没有看明白,请高手指点,感谢!!!!!
我没看懂你说的类是加法行为和类是减法行为
你要知道,这种二元操作符调用的魔法方法一般都是左边对象的魔法方法
魔法方法定义的是对对象实行某个操作时会调用的方法
而如你代码:
- class New_int(int):
- def __add__(self, other):
- return int.__sub__(self, other) # 这里是在进行减法,即a + b实际上返回的是a - b的结果
- def __sub__(self, other):
- return int.__add__(self, other) # 这里是在进行加法,即a - b实际上返回的是a + b的结果
复制代码
如你所见,c = b + a实际上就是c = 5 - 6,所以是-1
|
|