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