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 trialChad Goldsworthy
4,209 Points__iadd__ changes the data type?
I saw someone else ask this, but the question was still a bit unresolved. When including the iadd method in the class, it changes the data type. For example, with the class show in this video:
class NumString:
def __init__(self, value):
self.value = str(value)
def __str__(self):
return 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.value) + other
return int(self.value) + other
def __radd__(self, other):
return self + other
def __iadd__(self, other):
self.value = self + other
return self.value
Now, for example, if I were to use the regular add operator:
age = NumString(5)
age + 5
print(age.__class__.__name__) # this would return "NumString"
age.value # this would return "5"
But if I were to use the in place add operator:
age += 1
print(age.__class__.__name__) # this would return "int"
age.value # this returns an AttributeError
So using the dunder iadd method changes the variables data type, is this expected? What if you didn't want it to change the data type?
2 Answers
Chris Freeman
Treehouse Moderator 68,441 PointsGood question. The behavior of __iadd__
is up to the designer. In this case, __iadd__
method, self + other
is evaluated which triggers a call to __add__
. The method __add__
returns an int
or a float
type object. This int
or float
is assigned to self.value
, but then the self.value
is returned. This is what is assigned to the left-side of the statement and where the new type comes from.
If you wanted to keep the object type as NumString
then __iadd__
should return self
instead of self.value
:
class Numstring:
def __iadd__(self, other):
self.value = str(self + other) # use str() to keep value correct
return self
>>> age = NumString(5)
>>> age.value
'5'
>>> age += 6
>>> age
<__main__.NumString object at 0x7f630f78a860>
>>> age.value
'11'
>>> age = NumString(5)
>>> age.value
'5'
>>> age + 7
12
>>> age.value
'5'
>>> age += 7
>>> age.value
'12'
>>> type(age)
<class '__main__.NumString'>
Post back if you have more questions. Good luck!
Chad Goldsworthy
4,209 PointsA ha ! I get it now, thank you Chris.