4 ms·
Gotcha, I see where we differ. I've exclusively programmed in Python and since int, str and tuple are immutable in Python, I've always assumed "+=" operators cr
by iknownothow 4y ago
Gotcha, I see where we differ. I've exclusively programmed in Python and since int, str and tuple are immutable in Python, I've always assumed "+=" operators create copies and don't update the object.
- kazinator 4y ago> int is immutable But what does that have to do with assignment? >>> a = 3 >>> a += 4 >>> print(a) 7 3 and 7 are immutable, yet a takes on those objects. Obviously, this is inspired by the C += operator, and behaves accordingly, when it's not being weird.
- iknownothow 4y agoIf you go back to the original comment from the user praptak, you will notice in his example the assignments "obj.a += (2,)" and "obj.b += [2,]". These assignments work exactly as expected no matter which school of thought you come from. The difference is in how the Class attributes are affected i.e. the values of "A.a" and "A.b". # obj.a += (2,) has no impact on A.a since tuples # are immutable and copies are made. # This is unexpected from a C/C++ intuition. >>> print(A.a) (1,) # obj.b += [2,] has an indirect impact on A.b # since lists are mutable and updates are made in place. # This is unexpected for beginners in Python since it # deviates from how int, str and tuples behave as "+=" # can be used for int, str, tuples and lists. >>> print(A.b) [1, 2] Edit: formatting
- dragonwriter 4y ago> These assignments work exactly as expected no matter which school of thought you come No, they don't. obj.b does not exist, and no assignment to it takes place, and there is no “indirect effect”. A.b exists, and because class attributes can be accessed as if they were members on instances, and because A.b has an implementation of in-place addition, that implementation is called on A.b instead of an assignment to obj.b. That is the only thing that happens as a result of the statement that looks like it might be an assignment to obj.b. The effect on A.b is the only action, not an indirect effect of an assignment.