下面的代码抛出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
,代码运行但不打印任何内容。这没有任何意义,因为根据这篇文章,Python 中的 __str__ 和 __repr__ 之间的区别,省略__str__
会调用__repr__
,但这里似乎没有发生。
相反,如果我保持对super
和 add的调用__str__ = __repr__
,那么我会得到预期的输出并且没有递归。
有人可以解释为什么存在无限递归,为什么每次更改都会解决无限递归,以及为什么一个修复可能优于另一个修复?