On Nov 22, 8:38 pm, Roy Smith <r...@panix.com> wrote: > In article <4b0a01a...@dnews.tpgi.com.au>, Lie Ryan <lie.1...@gmail.com> > wrote: > > > The semantic of the in-place operator is something like: > > x += y > > becomes > > x = x.__iadd__(y) > > > thus > > foo.bar += baz > > becomes > > foo.bar = foo.bar.__iadd__(baz) > > > So the call sequence is, > > foo.__getattr__('bar') ==> x > > x.__iadd__(baz) ==> y > > foo.__setattr__('bar', y) > > I don't get where the __setattr__() call comes from in this situation. I > thought the whole idea of __iadd__(self, other) is that it's supposed to > mutate self. So, why is there another assignment happening after the > __iadd__() call?
Non-mutable types can also use += syntax. x = MagicalNumber(42) x += 5 # x gets reassigned to MagicalNumber(47) There is nothing that says that __iadd__ has to return self, but if you are designing a mutable type, you will generally do that. http://docs.python.org/reference/datamodel.html ''' These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These 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). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, to execute the statement x += y, where x is an instance of a class that has an __iadd__() method, x.__iadd__(y) is called. If x is an instance of a class that does not define a __iadd__() method, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y. ''' -- http://mail.python.org/mailman/listinfo/python-list