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
Philip Schultz
11,437 Pointsself vs self.value - magic methods
Can someone help me understand the code below? Why are we using self.value in some cases and just self in others? For example, in the int we use return 'int(self.value)', but in the add we use the 'int(self)'.
class NumString:
def __init__(self, value):
self.value = str(value)
def __str__(self):
return str(self.value)
def __int__(self):
return int(self.value)
def __float__(self):
return float(self.value)
def __add__(self, other):
if '.' in self.value:
return float(self) + other
return int(self) + other
def __radd__(self, other):
return self + other
def __iadd__(self, other):
self.value = self + other
return self.value
1 Answer
andren
28,558 PointsWhen you call int(self) Python looks at the object's __int__ method in order to figure out how to convert the object to an int. So calling int(self) inside the class is essentially the same as calling __int__. And since __int__ returns int(self.value) you end up with int(self) and int(self.value) evaluating to the same value.
If the __int__ method did not exist, or returned a different value then they would not act the same. Also you cannot use int(self) within the __int__ method, as that would result in an infinite loop of the method calling itself over and over. Those principles also holds true for float(self) as that results in the __float__ method being called.
Philip Schultz
11,437 PointsPhilip Schultz
11,437 PointsThanks! It seems obvious now. I guess I didn't realize that magic methods are being implicitly called within the methods of the same class. Is this design approach only valid if the object has one attribute? What if you have an object of a.....Customer lets say, and there are multiple attributes. You couldn't say simply 'int(self)' in the
__add__method right? You have to say something like self.sale or self.refund to certain calculations, right? How would one set that up?