Date: February 5th 2016
Last updated: February 6th 2016
The super method returns an object of the parent class. Super is almost always used for multiple inheritance. It might not matter so much for inheritance from a single parent class.
Here are some useful resources:
- how to use super
- python 201: what is super (and links within)
- super considered super
- using super effectively
- structuring super calls
The following example was inspired by the content in python 3: object oriented programming by Dusty Phillips.
A useful part of the following code occurs when Clients() is instantiated. Both name and phone number are added to my_contacts list. This is because super calls the init method in Contacts which appends the contact information.
class ContactList(list): pass # note that in python 2.7 Contacts must inherit from object class Contacts(object): my_contacts = ContactList() def __init__(self, name): self.name = name self.my_contacts.append(self) class Clients(Contacts): def __init__(self, name, phone): # add the new attribute for Clients self.phone = phone # make sure super calls THIS class (Clients)and not the one # you are trying to inherit from! I kept trying to # call super(Contacts, self) which 'obviously' failed super(Clients, self).__init__(name) # another python 2.7 option # super(self.__class__, self).__init__(name) # python 3 is different... # super().__init__(name) gf = Contacts('Jane') me = Clients('Mike', '0247324004') # dont instantiate... Contacts('Richard') #returns: <__main__.Contacts object at 0x7f69742ef090> [c.name for c in me.my_contacts] #returns: ['Jane', 'Mike', 'Richard'] # note that Richard still made the contacts list (class method of Contacts) # note that Mike is also in the contacts list (name is initialised from Contacts)
The following example was inspired by content in Python in a nutshell by Alex Martelli.
class base(object): def mymethod(self): print "base method" class satellite(base): def mymethod(self): print "satellite method" super(satellite, self).mymethod() satellite().mymethod() #returns: #>>> satellite method #>>> base method