I have been working on a multiple inheritance code which looks similar to this:
class Document():
def save(self, x):
print "inside Document from " + x
class Cdm(object):
def save(self,x):
print "inside Cdm from " + x
super(Cdm,self).save('Cdm')
class Contacts(Cdm, Document):
def __init__(self):
self.save('Contacts')
This is the result I get when I create an instance of Contacts.
> c = Contacts()
< inside Cdm from Contacts
< inside Document from Cdm
Now this is just weird, possibly to my eye. I might have misunderstood something. As you can see, the class Contacts inherits from cdm and Document. I am trying to use the save method of Cdm from Contacts. But Cdm inherits from object and does not have a super class method called save yet it calls the save function from Document class. In the program what I am working this is the behaviour I want but I am worried as theoretically it should not work or at least I think.
Do you have any comments on this. Or have I misunderstood Python’s inheritance.
As Python documentation says:
In that situation,
super(Cdm,self).save('Cdm')will call the version ofsave()which is next in method resolution order. In that case it is thesave()method in theDocumentclass because it is a sibling class ofCdm(i.e. it is the second base class ofContacts).A great practical explanation of
super()can be found here: Python’s super() considered super!