魔方方法__add__和__radd__的再次疑问
本帖最后由 wbzxz 于 2023-6-19 23:32 编辑各位老师,前面问过类似的问题,各位老师(@歌者文明清理员、@isdkz、@sfqxx )给了我很大帮助,因为我表述不清,我一直未得到自己想要的结果,所以我把问题进行了重新整理,再次请教各位老师
class S(str):
def __add__(self, other):
return len(self) * len(other)
class S1(str):
def __add__(self, other):
return NotImplemented
class S2(str):
def __radd__(self, other):
return len(self) + len(other)
s = S('FishC')
s1 = S1('Apple')
s2 = S2('Banana')
print("'nwu' + s:", 'nwu' + s)
print("'nwu' + s1:", 'nwu' + s1)
print("'nwu' + s2:", 'nwu' + s2)
print('s + s2:', s + s2)
运行结果:
'nwu' + s: nwuFishC
'nwu' + s1: nwuApple
'nwu' + s2: 9
s + s2: 30
请各位老师能否分析一下,代码中这四个式子进行运算时,是怎么调用了__add__方法和__radd__方法的,分别调用了哪个对象的什么方法?
页:
[1]