【问题标题】:maximum recursion depth exceeded when exec `repr()`exec `repr()` 时超出最大递归深度
【发布时间】:2016-11-10 16:22:57
【问题描述】:
class A(object):
    def xx(self):
        return 'xx'


class B(A):
    def __repr__(self):
        return 'ss%s' % self.xx

b = B()
print repr(b)

我写__repr__方法的时候忘记调用self.xx了。

为什么这些代码会导致RuntimeError: maximum recursion depth exceeded while getting the str of an object

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

【问题讨论】:

  • @skyking:是的,OP 意识到了这一点。他们在问题中声明他们忘了打电话给self.xx

标签: python recursion repr


【解决方案1】:

会发生这样的事情:

  • %sself.xx 呼叫 str(self.xx)
  • 一个方法没有__str__,所以在它上面调用__repr__
  • 方法的__repr__selfrepr() 合并为<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__>>
    
  • self__repr__ 尝试使用'ss%s' % self.xx

所以你有一个无限循环。

【讨论】:

    猜你喜欢
    • 2013-12-01
    • 2017-03-24
    • 2011-12-31
    • 2017-08-09
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多