exec `repr()` 时超出了最大递归深度

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.

我的英语很差,希望你们能理解这些。非常感谢!

Mar*_*ers 5

这是发生的事情:

  • %sself.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

所以你有一个无限循环。