pon*_*der 1 python recursion repr
class A(object):
def xx(self):
return 'xx'
class B(A):
def __repr__(self):
return 'ss%s' % self.xx
b = B()
print repr(b)
Run Code Online (Sandbox Code Playgroud)
当我写__repr__方法时,我忘记调用self.xx.
为什么这些代码会导致RuntimeError: maximum recursion depth exceeded while getting the str of an object.
我的英语很差,希望你们能理解这些。非常感谢!
这是发生的事情:
%s在self.xx通话str(self.xx)__str__,所以__repr__改为调用它。的__repr__一种方法结合了repr()的self为<bound method [classname].[methodname] of [repr(self)]>:
>>> class A(object):
... def xx(self):
... pass
...
>>> A().xx
<bound method A.xx of <__main__.A object at 0x1007772d0>>
>>> A.__repr__ = lambda self: '<A object with __repr__>'
>>> A().xx
<bound method A.xx of <A object with __repr__>>
Run Code Online (Sandbox Code Playgroud)在__repr__中self尝试使用'ss%s' % self.xx
所以你有一个无限循环。