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 Object-Oriented Python Advanced Objects Controlling Conversion

Suraj Shah
Suraj Shah
1,055 Points

magic methods

The explanation of how the str method (or any other magic method for that matter) works is very unclear.

Please could you explain in context of the characters.py example used by Kenneth in the video i.e. what does returning self.class.name and self.name actually do? How are these two things different?

Your help is really appreciated

1 Answer

Steven Parker
Steven Parker
231,186 Points

So "self.name" is an instance variable, and is explicitly created in the code anytime you create a new instance when you pass the name in as an argument to the constructor. You can see this being done in the __init__ method in the video. Kenneth passes his own name in during the construction and it returns back.

But "self.__class__.__name__" is a special variable set up for you by the system. It contains the name of the class that was used to create the instance. That's why in the video you can see that it returns "Thief".

Could you explain what the str does. please help me.

Steven Parker
Steven Parker
231,186 Points

I assume you mean the "magic" method "__str__" ("dunder str")? It's called automatically anytime the object is converted into a string. For example, if the object is passed as an argument to the "format" method.