为了账号安全,请及时绑定邮箱和手机立即绑定

python 3.5中 为什么无法重写魔法方法?

python 3.5中 为什么无法重写魔法方法?

wvguugvvc 2017-08-13 20:14:43
在自学python3.5.中,尝试重写魔法方法,为什么没有效果?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(3) b=New_int(5) print(a+b)代码输出还是8,没有调用我重新定义过的两个方法,请问是哪里有问题?初学者,不太明白,谢谢大神
查看完整描述

4 回答

?
孤独的小猪

TA贡献232条经验 获得超302个赞

重写魔法方法是生效的,刚才试了一下,是因为你重写的时候,add前后都少写一个下划线。

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(3)
b=New_int(5)
print(a+b)


查看完整回答
1 反对 回复 2017-08-14
?
angie

TA贡献56条经验 获得超8个赞

加是 __add__  (前后都是 2 个下划线)。减都知道这样写,加就不知道,,,

查看完整回答
反对 回复 2017-08-13
  • 4 回答
  • 0 关注
  • 2154 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信