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

Python Object-Oriented Python Advanced Objects Math

__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
MOD
Chris Freeman
Treehouse Moderator 68,457 Points

Good 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!!