函数内部的函数会导致无限递归

2024-09-29 19:35:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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)

我不小心省略了括号,attr变成了函数而不是字符串。但是,当我调用print(X)时,它进入了无限递归。在

错误代码如下。在

^{pr2}$

File "Some Folder/classtools.py", line 18, in __repr__

return '[Class: %s]\n%s' % (self.__class__.__name__, attr)

[Previous line repeated 244 more times]

RecursionError: maximum recursion depth exceeded while calling a Python object

我试图调试,但找不到这种行为的确切原因。即使我不小心留下了括号,它也应该打印<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()

Tags: keynameinselfreturndefcountall
1条回答
网友
1楼 · 发布于 2024-09-29 19:35:12

这是因为绑定方法的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!>>'

请注意,我在这里做了一些跳跃,它们是:

  • '%s' % x大致相当于{}
  • 当某个东西没有定义__str__,它会回到__repr__(方法描述符就是这样)

在检索类的repr时,您将得到以下循环:

  • AttributeDisplay.__repr__=>
  • AttributeDisplay.gatherAttributes.__repr__=>
  • AttributeDisplay.__repr__(类的repr作为绑定方法repr的一部分)=>
  • 。。。在

相关问题 更多 >

    热门问题