哪位巨佬能解释一下为什么这个
哪位大佬解答一下为什么结果会是13>>> class s1(str):
def __add__(self,other):
return NotImplemented
>>> class s2(str):
def __radd__(self,other):
return len(self)+len(other)
>>> ss1 = s1("hhhh")
>>> ss2 = s2()
>>> ss1 + ss2
13 本帖最后由 jackz007 于 2022-10-19 01:31 编辑
>>> class s1(str):
def __add__(self,other):
return NotImplemented
>>> class s2(str):
def __radd__(self,other):
return len(self)+len(other)
>>> ss1 = s1("hhhh")
>>> ss1
'hhhh'
>>> ss2 = s2()
>>> ss2
''
>>> ss1 + ss2
13
>>>
执行 ss1 + ss2,首先,会调用 ss1 . __add__() 方法,可是,其返回值 NotImplemented 表示本方法尚未实现,本对象放弃处理,于是,就会转向调用 ss2 . __radd__(),并将 2 个字符串长度相加的结果 13 作为了返回值。
页:
[1]