Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

I'm not sure what's the point of the magic methods string conversion example

I don't understand what is the advantage of using the dunder string conversion (str) method as oppose to just writing a normal method that converts an instance into a string.

For example:

  def __str__(self):

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

does the exact same thing as the following:

  def strconv(self):

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

the difference is that I didn't use the dunder magic method for the method name.

1 Answer

Daniel Turato
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree seal-36
Daniel Turato
Java Web Development Techdegree Graduate 30,124 Points

You're right, there is no real difference in the output from both methods. However, magic methods are already built with python already so it's a standard to use these when you need them.