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
。
我的英语很差,希望你们能理解这些。非常感谢!
事情是这样的:
%s
在 self.xx
调用 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
所以你有一个无限循环。
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
。
我的英语很差,希望你们能理解这些。非常感谢!
事情是这样的:
%s
在self.xx
调用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
所以你有一个无限循环。