Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Trouble understanding some concepts of OOP and max recursion error. Python

Hello, this is my code;

class Polo:
    def __init__(self,value):
        self.value = value


    def __str__(self):
        return str(self.value)

when I run this code and create an instance like;

age = Polo(30)

age.value
#output 30

print(age)
#output 30

I don't understand why the instance "age" has the same value as "age.value".

Isn't "age" an instance of "Polo" class? and "value" an attribute? aren't these supposed to be two different things? but why does an instance "age" gives the same output as "age.value"?

2nd question: MAX RECURSION ERROR

I understand that "max recursion error" occurs when a function keeps executing itself till a condition is met, looking at the code below;

class Polo:
    def __init__(self,value):
        self.value = value


    def __str__(self):
        return str(self) # Removed (.value)

when I replaced "return str(self)" instead of "return str(self.value)" a max recursion error occurs, but what I don't understand is that why the function;

def __str__(self):
        return str(self) # Removed (.value)

keeps executing itself, shouldn't it just give an error instead of executing itself?

I would really appreciate your detailed answers, Thank you!

1 Answer

Steven Parker
Steven Parker
243,201 Points

When you print the object itself, the system has no idea how to do that so it looks for the "__str__" method and runs that. Your class then return the "value" expressed as a string for printing.

And for question 2, what kind of error were you expecting? When you write "str(self)" the system calls "__str__" again to convert the class into a string, so it is essentially calling itself.

I somewhat got the idea of the answers, however, can the code below be possible;

class Polo:
    def __init__(self,value):
        self.value = value


    def __str__(self):
        return str("{} is an instance of {}".format(self,self.__class__))

I need to print out the name of my instance and the class it belongs too, but I get a recursion error, or maybe there is another way to get what I want?

Steven Parker
Steven Parker
243,201 Points

An instance doesn't know it's own name, besides it could have more than one. So leave off "self" to avoid recursion:

        return "an instance of {}".format(self.__class__)