Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading augmented arithmetic assignments in python

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.

like image 201
Mel Avatar asked Feb 15 '10 16:02

Mel


1 Answers

You need to add return self to your method. Explanation:

The semantics of a += b, when type(a) has a special method __iadd__, are defined to be:

  a = a.__iadd__(b)

so if __iadd__ returns something different than self, that's what will be bound to name a after the operation. By missing a return statement, the method you posted is equivalent to one with return None.

like image 127
Alex Martelli Avatar answered Nov 15 '22 22:11

Alex Martelli