LLS*_*LLS 0 python recursion repr
我正在学习 Python,并尝试编写以下代码。
class AttributeDisplay:
'''Display all attributes of a class in __repr__.
It can be inherited.'''
def gatherAttributes(self):
'''Gather all attributes and concatenate them
as a string'''
def getAttributeNameAndValue(key):
return '[%s] - [%s]' % (key, getattr(self, key))
return '\n'.join((map(getAttributeNameAndValue, sorted(self.__dict__))))
def __repr__(self):
'''Print all attributes'''
attr = self.gatherAttributes() # omitting () results in infinite recursion
return '[Class: %s]\n%s' % (self.__class__.__name__, attr)
Run Code Online (Sandbox Code Playgroud)
我不小心省略了括号,attr 变成了一个函数而不是一个字符串。但是,当我调用 时print(X),它进入了无限递归。
错误代码如下。
def __repr__(self):
'''Print all attributes'''
attr = self.gatherAttributes # omitting () results in infinite recursion
return '[Class: %s]\n%s' % (self.__class__.__name__, attr)
Run Code Online (Sandbox Code Playgroud)
文件“Some Folder/classtools.py”,第 18 行,在 __repr__ 中
Run Code Online (Sandbox Code Playgroud)return '[Class: %s]\n%s' % (self.__class__.__name__, attr)[上一行重复了 244 次以上]
RecursionError:调用 Python 对象时超出了最大递归深度
我试图调试但找不到这种行为的确切原因。即使我不小心留下了括号,它也应该<function object ...>正确打印?
为什么__repr__在这种情况下它会调用自己?
提前致谢。
编辑:测试代码如下。
if __name__ == '__main__':
class TopTest(AttributeDisplay):
count = 0
def __init__(self):
self.attr1 = TopTest.count
self.attr2 = TopTest.count+1
TopTest.count += 2
class SubTest(TopTest):
pass
def test():
t1, t2 = TopTest(), SubTest()
print(t1)
print(t2)
test()
Run Code Online (Sandbox Code Playgroud)
这是因为repr绑定方法的 包含了它绑定到的对象:
>>> class C:
... def __repr__(self):
... return '<repr here!>'
... def x(self): pass
...
>>> C().x
<bound method C.x of <repr here!>>
>>> str(C().x)
'<bound method C.x of <repr here!>>'
Run Code Online (Sandbox Code Playgroud)
请注意,我在这里做了一些飞跃——它们是:
'%s' % x 大致相当于 str(x)__str__,它会回退到__repr__(方法描述符就是这种情况)在检索类的 repr 时,您最终会得到这个循环:
AttributeDisplay.__repr__ =>AttributeDisplay.gatherAttributes.__repr__ =>AttributeDisplay.__repr__ (类的代表作为绑定方法代表的一部分)=>| 归档时间: |
|
| 查看次数: |
999 次 |
| 最近记录: |