python super() in two mins.

Let's start with a simple class Contact that tracks the name and e-mail addresses of several people. The Contact class is responsible for maintaining a list of all contacts in a class variable, and for initializing the name and email of individual contact.
class Contact():
all_contacts = []
def __init__(self,name,email):
self.name = name
self.email = email
Contact.all_contacts.append(self)


Now, we want to change the behavior of this class. Our Contact class only allows to add name and email address, but what if we also want to add a phone number?

Well, one way is by creating a subclass that inherits the superclass, the newly created subclass method is automatically called instead of superclass's method. For Example :

class Friend(Contact):
def __init__(self, name , email, phone):
self.name = name
self.phone = phone
self.email = email

Any method can be overridden, not just __init__.

The Contact and friend class has duplicate code to set up name and email. Moreover, the friend Class is neglecting to add itself to the all_contacts list we have created on the Contact class.

What we need to do here is to find a way to execute the original __init__ method on the Contact class. That's what super function does, it returns the object as an instance of the parent class, allowing to call the parent method directly.

class Friend(Contact):
def __init__(self,name,email,phone):
super().__init__(name,email)
self.phone = phone


This gets the instance of the parent object using super and calls __init__ on that object passing the required parameters, and then does its own initialization, setting the phone attribute.

  1. A super() call can be made inside any method, not just __init__. This means all methods can be modified via overriding and calls to super.
  2.  The call to super can also be made at any point in the method; we don't have to make the call as the first line in the method.
    












Comments

Mahesh C. Regmi said…
nice one dai.

added:
class Child(A,B)
One more point, If you have multiple inheritance super will take the first included (A) class as super-class because of method resolution. If you want other one you can search from top-level hierarchy from the method A by doing super(A , self), this will exclude A from the search hierarchy. ^_^