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

Matthew Ison
Matthew Ison
5,989 Points

Delete __iadd__ and everything worked the same...

In this video it appears to be showing that iadd let's us store the numerical value in age(age += 1) and then add it to another number. However, I deleted the iadd function and age+=1, then age +5 gave the same output as when the iadd was in place.

So if it wasn't necessary for the example in the video, then what is an example where it's actually necessary?

1 Answer

Jeff Muday
Jeff Muday
Treehouse Moderator 28,715 Points

This can be a little confusing at first.

__iadd__ is the "inplace addition" operator. It is different than the __add__ method which simply returns the RESULT of the addition to another object. But instead the __iadd__ is 2 operations with one operator... it evaluates first then and replaces itself with a new object.

Since the addition is "inplace" it means that the value of object is modified in place. Its counterparts are __isub__ and iconcat for strings.

x = 3
# the iadd adds and modifies the object, 2 operations in one!
x += 1