1

I'm learning Python, and today istudied how to override operator.

This is a simple code:

class Team:
    def __init__(self, members):
        self.members = members

    def __repr__(self):
        names = ", ".join(p.name for p in self.members)
        return "<Team Object [{}]".format(names)

    def __iadd__(self, other):

        if isinstance(other, Person):
            self.members.append(other)
            return self

        elif isinstance(other, Team):
            self.members.extend(other.members)
            return self (????????????)

        else:
            raise TypeError("Tipi non supportati")

I inizialize two teams:

guido = Person('Guido','van Rossum')
tim = Person('Tim', 'Peters')
alex = Person('Alex', 'Martelli')
ezio = Person('Ezio', 'Melotti')
t1 = Team([guido, tim])
t2 = Team([alex, ezio])

now if do

t1 += t2
print(t1)

i got

with "return self" in iadd()

Team Object [Guido, Tim, Alex, Ezio]

without "return self" in iadd()

none

I don't understand why beacuse, in my opinion, method iadd changes the attribute of object so i should see this change without return any reference to same object

Christian Sicari
  • 121
  • 2
  • 13
  • Does this answer your question: https://stackoverflow.com/a/31546707/190597 ? – unutbu Mar 25 '18 at 17:17
  • @unutbu maybe yes when say " when __iadd__ is overriden, the x += y operation does NOT end with the end of __iadd__ method. Instead, it ends with x = x.__iadd__(y). In other words, Python assigns the return value of your __iadd__ implementation to the object you're "adding to", AFTER the implementation completes. This means it is possible to mutate the left side of the x += y operation so that the final implicit step fails" . The problem can be that x+=y is like write x = x.__iadd_(y), so if __iadd__() doesn't return x is null. Wait confirm – Christian Sicari Mar 25 '18 at 17:25

1 Answers1

1

+= is still an assignment operation. Python will assign the result of calling t1.__iadd__(t2) back to t1. If the method returns None (which it does if it doesn't have a return statement) then that is what will be assigned to t1; the object will be modified, but then lost.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895