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.

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 27,653 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