I’m new to Python so apologies in advance if this is a stupid question.
For an assignment I need to overload augmented arithmetic assignments(+=, -=, /=, *=, **=, %=) for a class myInt. I checked the Python documentation and this is what I came up with:
def __iadd__(self, other):
if isinstance(other, myInt):
self.a += other.a
elif type(other) == int:
self.a += other
else:
raise Exception("invalid argument")
self.a and other.a refer to the int stored in each class instance. I tried testing this out as follows, but each time I get ‘None’ instead of the expected value 5:
c = myInt(2)
b = myInt(3)
c += b
print c
Can anyone tell me why this is happening? Thanks in advance.
You need to add
return selfto your method. Explanation:The semantics of
a += b, whentype(a)has a special method__iadd__, are defined to be:so if
__iadd__returns something different thanself, that’s what will be bound to nameaafter the operation. By missing areturnstatement, the method you posted is equivalent to one withreturn None.