Reputation: 5068
I have run into a problem I can't explain:
class A:
def __init__(self, rid, title):
self.rid = rid
self.title = title
self.b = []
def __add__(self, other):
if type(other) == B:
self.b += [other]
def __str__(self):
return self.rid + ' - ' + self.title
def __repr__(self):
return str(self)
class B:
def __init__(self, rid, title):
self.rid = rid
self.title = title
b = B('123', 'abc')
a = A('345', 'cde')
print(a)
a += b
print(a)
The first print results in the expected output:
345 - cde
However, the second print (after the adding of b) results in:
None
Why is that? I am not changing the rid or the title of a
nor do I create new and uninitialized instance called a
, or am I?
Upvotes: 0
Views: 38
Reputation: 95622
The expression a += b
is a shorthand for: a = a.__add__(b)
As your __add__()
method returns None
that means you will assign None
to a
.
Upvotes: 2