[英]Python 3: maximum recursion depth exceeded while getting the __repr__ of a list
[英]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__
合並了self
的repr()
作為<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.