|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
问题一:是不是只有同类产生的对象才可以相加?我个人觉得这句话不太对:
class New_int(int):
def __add__(self, other):#自定义的加法
return int.__sub__(self, other)
def __sub__(self, other):#自定义的减法
return int.__add__(self, other)#调用int对象的加法
class New_int1(int):
def __add__(self, other):#自定义的加法
return int.__add__(self, other)
def __sub__(self, other):#自定义的减法
return int.__sub__(self, other)#调用int对象的加法
>>>a=New_int(2),b=New_int1(3) 然后计算a+b的结果是会按照a的魔法方法add去加的,那么问题来了,我如果计算a+b+b那么结果是会调用谁的魔法方法add来加?
2)上一个问题就引出了我的第二个问题。两个对象相加后的结果是什么?是一个什么类的是由谁决定的?
1. 不是,不管 other 是不是同类都将传递给 __add__
2. 假设 a + b,先调用 a.__add__(b),如果 a 没有 __add__ 方法或者在调用 a 的 __add__ 方法时出错了就会调用 b.__radd__(a) 。
特别地,如果 type(b) 是 type(a) 的子类,则优先调用 b.__radd__(a)。例子:
- >>> class A:
- def __add__(self, other):
- print('A 的 __add__ 方法被调用了')
-
- >>> class B(A):
- def __radd__(self, other):
- print('B 的 __radd__ 方法被调用了')
-
- >>> a = A()
- >>> b = B()
- >>> a + b
- B 的 __radd__ 方法被调用了
复制代码
|
|