iBug
iBug

Reputation: 37297

After self addition the object becomes None...?

Try this simple code (MCVE):

class Foo(object):
    def __init__(self, val):
        self.v = val

    def __add__(self, other):
        return Foo(self.v + other.v)

    def __iadd__(self, other):
        print('before iadd v = {}'.format(self.v))
        self.v = (self + other).v
        print('after iadd v = {}'.format(self.v))

    def __str__(self):
        return repr(self)

    def __repr__(self):
        return 'Foo.__repr__({})'.format(self.v)

a = Foo(3)
b = Foo(5)
a += b
print('Now a is {}'.format(a))

The output is

before iadd v = 3
after iadd v = 8
Now a is None

I suppose a += b should modify a in-place (and that's what I wrote in Foo.__iadd__(). That confused me for a long time. I expected that the last line should be

Now a is Foo.__repr__(8)

Upvotes: 1

Views: 326

Answers (1)

ramazan polat
ramazan polat

Reputation: 7900

Because you return nothing in the __iadd__ method. Try returning self.

Upvotes: 3

Related Questions