在自学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)
添加回答
举报
0/150
	提交
		取消
	
