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

在自学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,没有调用我重新定义过的两个方法,请问是哪里有问题?初学者,不太明白,谢谢大神

wvguugvvc
浏览 2159回答 4
4回答

孤独的小猪

重写魔法方法是生效的,刚才试了一下,是因为你重写的时候,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)

angie

加是 __add__  (前后都是 2 个下划线)。减都知道这样写,加就不知道,,,
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python