Aman Vernekar
Aman Vernekar

Reputation: 31

Calling print(self) under __str__ throws a RecursionError

I have defined a class called spam:

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

print(a)

The print statement in the end gives me the following error:

    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

What is going on here? What happens when I say print(self) under str(self)? What is causing the recursion?

Upvotes: 2

Views: 447

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140168

print calls str on the non-string object to be able to print it, which calls your __str__ member method.

Here is your recursion.

You define a __str__ method when you are able to convert your object to an "equivalent" string. If not, just leave the default (which prints the object type & address)

Note that __str__ should return something, not print. If you have some representative attribute, you could use it to return something interesting.

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)

prints:

object 'spam' with value 10

Upvotes: 9

Related Questions