在__str__下调用print(self)会引发RecursionError

时间:2018-10-07 19:17:30

标签: python python-3.x

我定义了一个称为垃圾邮件的类:

class spam():
    def __str__(self):
        print(self)
a = spam()

print(a)

最后的打印语句给我以下错误:

    Traceback (most recent call last):
  File "<pyshell#73>", line 1, in <module>
    print(a)
  File "<pyshell#51>", line 3, in __str__
    print(self)
  File "<pyshell#51>", line 3, in __str__
    print(self)
  File "<pyshell#51>", line 3, in __str__
    print(self)
  #same lines repeated several times
  RecursionError: maximum recursion depth exceeded

这是怎么回事?当我在str(self)下说print(self)时会发生什么?是什么导致递归?

1 个答案:

答案 0 :(得分:9)

Portfolio<Share> p = new Portfolio<>(); 在非字符串对象上调用print以使其能够打印,这将调用您的str成员方法。

这是您的递归。

可以将对象转换为“等效”字符串时,定义一个__str__方法。如果不是,则保留默认值(打印对象类型和地址)

请注意,__str__应该返回某些内容,而不是打印内容。如果您具有一些代表性的属性,则可以使用它返回一些有趣的东西。

__str__

打印:

class spam():
    def __init__(self,value):
        self.__value = value
    def __str__(self):
        return "object '{}' with value {}".format(self.__class__.__name__, self.__value)

a = spam(10)
print(a)