【发布时间】:2014-02-18 22:58:16
【问题描述】:
以下代码抛出RuntimeError: maximum recursion depth exceeded while getting the str of an object。我可以用两种不同的方式解决无限递归,但我不明白为什么每个修复都有效,因此不知道使用哪个,或者是否正确。
class FileError( Exception ):
def __init__( self, filename=None, *a, **k ):
#Fix 1: remove super
super( FileError, self ).__init__( self, *a, **k )
self.filename = filename
def __repr__( self ):
return "<{0} ({1})>".format( self.__class__.__name__, self.filename )
#Fix 2: explicitly define __str__
#__str__ = __repr__
print( FileError( "abc" ) )
如果我删除 super,代码会运行但不会打印任何内容。这没有任何意义,因为根据这篇文章,Difference between __str__ and __repr__ in Python,省略__str__ 将调用__repr__,但这似乎不会发生在这里。
如果我保持对super 的调用并添加__str__ = __repr__,那么我会得到预期的输出并且没有递归。
有人可以解释为什么存在无限递归,为什么每次更改都会解决无限递归,以及为什么一种修复可能优于另一种修复?
【问题讨论】:
-
__repr__未被用作__str__的原因是基本异常定义了__str__。
标签: python recursion custom-exceptions repr