|
|
10鱼币
- class Nstr:
- def __init__(self, arg=''):
- if isinstance(arg, str):
- self.total = 0
- for each in arg:
- self.total += ord(each)
- else:
- print("参数错误!")
- def __add__(self, other):
- return self.total + other.total
- def __sub__(self, other):
- return self.total - other.total
- def __mul__(self, other):
- return self.total * other.total
- def __truediv__(self, other):
- return self.total / other.total
- def __floordiv__(self, other):
- return self.total // other.total
复制代码
这是小甲鱼42课课后作业的答案,为什么返回的是self.total和other.total而不是self和other呢
还有,在下列这些情况下,- class Nstr(str):
- def __sub__(self, other):
- return self.replace(other, '')
复制代码
- class New_int(int):
- def __add__(self,other):
- return int.__sub__(self,other)
复制代码
什么时候该返回self.xxxxx,什么时候该返回int.xxxxxxxx(或者继承的其他类) |
最佳答案
查看完整内容
这种情况下是不可以写self和other的
那样会变成死循环的
比如
当执行 a+b 时,会调用类中_add_方法,而返回值是 self + other,self 对应的就是a,other 对应的就是b,相当于又是 a+b,进而又去调用__add__方法,结果就变成了递归的形式,一直循环下去
后面那两个问题在http://bbs.fishc.com/forum.php?mod=viewthread&tid=73865&extra=page%3D1%26filter%3Dtypeid%26typeid%3D392 这里有说,不知道你是否能明白
|