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 trialAndrew McLane
3,385 PointsMagic Methods Help
Hi,
Not sure why we need a double underscore method to make floats, strings, etc.
Why in the init method can we not just use the conversions (str(),float(),etc.)?
So far in our python course we don't have to create a whole new function for doing this.
Thanks!
1 Answer
Wade Williams
24,476 PointsYou use a "Magic Method" to take-over what happens when a built in function is applied to your object.
For instance in the video, he uses the str() on his Thief object "Kenneth", but when he uses str(Kenneth) it only prints out a string representation of the object pointer in memory (<thieves.Thief object at 0x........>) and what he really wants str() to do is print out the name associated with that instance of the class which you can do my using str in your class.
Here's a code example, you can see that my classes str method hijacks what python does when str() is applied to my num_five int variable vs my num_five object variable.
class pointless:
def __init__(self):
pass
def __str__(self):
return "This is a string representation of the number 5"
# prints 5 as a string
num_five = 5
print(str(num_five))
# prints "This is a string representation of the number 5"
num_five = pointless()
print(str(num_five))
Andrew McLane
3,385 PointsAndrew McLane
3,385 Pointsso when you're using float, int, str, ect in console, it will actually use those methods rather than just give us info about the object, correct?
Wade Williams
24,476 PointsWade Williams
24,476 PointsCorrect, so when you have a __str__ "Magic Method" in your class it will run the classes str() method and not python's built in str() method when str() is applied to an instance of that class.