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.

anthony pizarro
1,983 Points__iadd__
why do we need __iadd__
kenneth said we need it to add age += 1
but i tried it without the __iadd__
and it was able to run just fine
age was updated
1 Answer

Chris Freeman
Treehouse Moderator 67,995 PointsGood question! You are correct, in Kenneth's code, with or without __iadd__
you get the same result: an int. This is arguably not the correct result. Ideally, an __iadd__
method should keep the type of object the same. As mentioned in the Python docs:
These [augmented arithmetic assignments] methods should attempt to do the operation in-place (modifying
self) and return the result (which could be, but does not have to be,
self).
So the __iadd__
method should look more like:
def __iadd__(self, other):
print(f"{self.value} running __iadd__ with value: {other}")
self.value = str(self + other)
return self
Since Kenneth's version of __iadd__
sets self.value
to self + other
, it is now an int
type instead of a str
type and the returned int
value is assigned to the original value. This is the same result as if __add__
was used instead.
To complete the options, if __iadd__
is not implemented, then __add__
is used as a work-around:
a += b
# becomes
tmp = a + b
a = tmp
Post back if you have more questions. Good luck!!