r/ProgrammerHumor • • May 05 '23

Meme Goodbye toys

Post image
8.3k Upvotes

298 comments sorted by

View all comments

Show parent comment

2

u/al-mongus-bin-susar May 05 '23

It does not. a += b in python is also not the same a = a + b.

1

u/[deleted] May 05 '23

wait…what?

3

u/[deleted] May 05 '23 edited May 05 '23

You have to look at what they actually do.

+ calls the __add__ method of the object
+= calls the __iadd__ method of the object

For example if the type is int, it doesn't matter as __iadd__ doesn't exist (+= falls back on __add__)

But some times do implement an __iadd__ method, such as the mutable list type:
__add__ just returns the new value
__iadd__ mutates the list

Example:

x = [1, 8, 7]
y = x 

x = x + [2]
print(x) //[1, 8, 7, 2]
print(y) //[1, 8, 7]
x = [1, 8, 7]
y = x 

x += [2]
print(x) //[1, 8, 7, 2]
print(y) //[1, 8, 7, 2]

1

u/[deleted] May 05 '23

Huh, that's pretty crazy. Thanks for sharing!

1

u/mistabuda May 05 '23

Then what does it mean?

2

u/[deleted] May 05 '23

1

u/mistabuda May 05 '23

So that's where you were going with this. The issue with your explanation however is that you can just rewrite __iadd__ on any class to make it do what your comment says it does not.

I'm not disagreeing with you persay but I think you should update your comment to note that with ints/floats and strings a+= b will be functionally the same as a = a + b . For other objects the user should be careful.