I'm taking a Python course and the exercise is to create a class in which you can append a dictionnary to another by typing : dict1 = dict1 + dict2
So this is done by creating an __add__
method in the class, because dict1 + dict2
is the same as typing dict1.__add__(dict2)
, right ? Except that if I type those 2 commands they don't return the same value. This is an extract of my code :
class zDict(dict):
...
def __add__(self, otherDict):
otherDict = [(k,v) for k,v in otherDict.items()]
print("passed through zDict.__add__") #just to make sure
for key, value in otherDict:
self[key]=value
...
So now if we run this with 2 zDict objects, dict1 = {'a':1,'b':2,'c':3}
and dict2 = {'d':4,'e':5}
for examples, here are the results (Python 3.6.6) :
>>> dict1.__add__(dict2)
passed through zDict.__add__
>>> dict1
>>> {'a':1,'b':2,'c':3,'d':4,'e':5}
>>> type(dict1)
>>> <class '__main__.zDict'>
RESTART
>>> dict1 += dict2
passed through zDict.__add__
>>> dict1
>>> type(dict1)
>>> <class 'NoneType'>
So I don't understand there. I typed the same thing but got different results. dict1 = dict1 + dict2
is the same as typing dict1 += dict2
, which is the same as typing dict1 = dict1.__add__(dict2)
, right ? And I made sure they pass through the same method with print. It can't come from the dict class
, because it doesn't have any __add__
method. Maybe it passes through a method from a parent class like object, who changes the type to NoneType
? How can I check that, and prevent it ?