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 trialSimon Amz
4,606 PointsInterest of magic method
In the video "Comparing and combining dice", I still don't really understand the interest or upside to use magic methods as __int__
or __eq__
.
Couldn't we use the basic function already computerized?
Thanks for your help
[Mod: added ` escape formatting -cf]
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsGood question! When defining a class, additional methods are needed if you wish to treat the object is special ways, such as comparing or adding them.
Say, I had a Rock
class. How would I know if one rock was bigger than another or what a "sum of rocks" equals? It is the magic methods that allow using classes in comparisons or other math statements.
class Rock:
def __init__(self, size=0):
self.size = size
One way to compare rocks would be by having a number representation of the rock. Defining an __int__
method says "here is an integer representation of this rock"
def __int__(self):
return self.size
Now I can use int()
on any Rock
instance and get back its size
value. To compare this rock to a value
def __gt__(self, other):
return int(self) > int(other)
>>> class Rock:
... def __init__(self, size=0):
... self.size = size
... def __int__(self):
... return self.size
... def __gt__(self, other):
... return int(self) > int(other)
... def __add__(self, other):
... return int(self) + int(other)
...
>>> r1 = Rock(3)
>>> r2 = Rock(6)
>>> r1 > r2
False
>>> r2 > r1
True
>>> r2 + r1
9
Without these magic methods, comparisons and object math would not be possible.
Post back if you have more questions. Good luck!!
Adrian Diaz
3,500 PointsAdrian Diaz
3,500 Pointswell cant you just add this code?: self.size = int(size)
Then when you try and compare the two instances you can just do this: r1.size > r2.size
This seems like an easier way of getting the same result.
Im having difficulty understanding the reason for this magic method. Especially since the only thing that should ever go in the size attribute is an integer.
I would like if kenneth explained why we are using a particular magic method in detail