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

def __str__(self): return "{}: {}".format(self.__class__.__name__, self.name)

When I add this line to Characters nothing is printed when I run play.py. How does the teacher get "Thief: Kenneth" from just the Method Return with no print command?

I had to add this to play.py to get it to output the returned value: print(kenneth.str())

Can you post a snapshot of your workspace? Click the camera icon in the upper right corner, then click 'Take Snapshot', then post the link that is created here.

1 Answer

Steven Parker
Steven Parker
231,268 Points

In the video, there is a print command that displays "Thief: Kenneth" — it's in the play.py file: "print(kenneth)"

And the reason that it works (and you don't need "print(kenneth.__str__())") is because the system automatically invokes the __str__ method on a thing when you print it.

Thanks so much. In general I love Treehouse but this section and this instructor I find hard to follow. So when you print an instance of a class, Python looks for a str method..what of there is more than one..does it print all of them.. the first one?

Steven Parker
Steven Parker
231,268 Points

Method names must be unique, you can only have one method of any particular name in a class.

TY!..can you have an str method in a class and import another class that has an str? If yes what happens then when you print?

Steven Parker
Steven Parker
231,268 Points

Method names only need to be unique within the same class. Methods in other classes are completely separate and will not conflict.

ty...if there is a strmethod in both a class and you import another class that has a_str_ method, what will happen when you use print()..how will python know which one use?

Steven Parker
Steven Parker
231,268 Points

It only uses the method defined for that same class (the class of the thing you are printing). Methods in other classes (even if they have the same name) are completely separate.

Think of method and class like city and state. If you get on a plane going to Arlington, Virginia it doesn't land in Arlington, Texas.