user2229219 user2229219 - 1 year ago 56
Python Question

How do I make "x += 5" (with x a custom class) add to a property of x?

I have a class like this:

class C(object):
a = 5
def __iadd__(self, other):
self.a += other

I would like to be able to do something like:

b = C()
b += 7

And have b the same, but with 7 added to b.a. However, if I actually run this, it turns b into a NoneType object. I assume this is because C.__iadd__ does not return anything.

Do I have to make C.__iadd__ return a copy of self with self.a modified? Is there a way to implement this kind of addition without copying the entire object and returning that?

Answer Source

You forgot to return self from the __iadd__ method:

def __iadd__(self, other):
    self.a += other
    return self

From the object.__iadd__() documentation:

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).

Without an explicit return statement, a function returns None as a default, so b += 7 produced None which is the result of the assignment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download