簡體   English   中英

exec`repr()`超過最大遞歸深度

[英]maximum recursion depth exceeded when exec `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)

當我編寫__repr__方法時,我忘記了調用self.xx

為什么這些代碼會導致RuntimeError: maximum recursion depth exceeded while getting the str of an object

我的英語不好,希望你們能聽懂這些。 非常感謝你!

這是發生了什么:

  • self.xx上的%s調用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

所以你有一個無限循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM