|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在课程中,小甲鱼讲到用New_int定义了一个加减法相反的类,两个New_int的实例a和b做运算,加减法互换了。
我好奇如果一个New_int的实例a和另一个正常的int实例b,做加减运算会怎么样,编程如下:
- 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 = int(5)
- print(a + b)
- print(a - b)
- print(b + a)
- print(b - a)
复制代码
为何只有 a + b会报错,其他都可以正常运算?求解答,谢谢各位大牛!
- Traceback (most recent call last):
- File "D:/program files/python/test/lesson42.py", line 9, in <module>
- print(a + b)
- File "D:/program files/python/test/lesson42.py", line 3, in __add__
- return int.__sub__(self.other)
- AttributeError: 'New_int' object has no attribute 'other'
复制代码
return int.__sub__(self.other)中间是逗号
|
|