马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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('s1+s2:', s1 + s2)
print('s2+s1:', s2 + s1)
print('s + s1:', s + s1)
# print('s1 + s:', s1 + s)
print('s + s2:', s + s2)
print('s2 + s:', s2 + s)
print("s + 'nwu':", s + 'nwu')
print("'nwu' + s:", 'nwu' + s)
# print("s1 + 'nwu':", s1 + 'nwu')
print("'nwu' + s1:", 'nwu' + s1)
print("s2 + 'nwu':", s2 + 'nwu')
print("'nwu' + s2:", 'nwu' + s2)
运行结果如下:
s1+s2: 11
s2+s1: BananaApple
s + s1: 10
s1+s 运行错误
s + s2: 11
s2 + s: BananaFishC
s + 'nwu': 8
'nwu' + s: nwuFishC
s1 + 'nwu' 运行错误
'nwu' + s1: nwuApple
s2 + 'nwu': Banananwu
'nwu' + s2: 9
请教各位老师,在魔方方法中学习中,个人理解是,先看左边对象有没有__add__方法, 如果左边对象没有__add__方法,或者返回NotImplemented是,看右边有没有__radd__方法。
但是print("'nwu' + s2:", 'nwu' + s2)这个的结果我不太理解,我以为结果应该是nwuBanana,但是为什么是9呢, 我想着’nwu‘是一个字符串对象,应该有__add__方法啊;比如print("'nwu' + s:", 'nwu' + s)这个结果就是nwuFishC, 好像是符合我理解的。到底我是哪里理解错误呢,请指点。
|