- Python super() Function
- Syntax
- Parameters
- Example 1: How to Use the super() function in Python
- Example 2
- Example 3: Method overriding
- Python super() with __init__()
- Example
- Super() function with Multiple Inheritances
- Example
- Super() function with Multi-Level Inheritance
- Example
- Python Multiple Inheritance and MRO
- Example
- Python Inheritance
- Create a Parent Class
- Example
- Create a Child Class
- Example
- Example
- Add the __init__() Function
- Example
- Example
- Use the super() Function
- Example
- Add Properties
- Example
- Example
- Add Methods
- Example
Python super() Function
Python super() function is “used to refer to the parent class or superclass.” It allows you to call methods defined in the superclass from the subclass, extending and customizing the functionality inherited from the parent class.
Syntax
Parameters
It returns a proxy object which represents the parent’s class.
Example 1: How to Use the super() function in Python
To call a super() function in Python, create a parent and child class, inherit the parent class to the child class, and then call the super() method from the child class.
class MyParentClass(): def __init__(self): pass class SubClass(MyParentClass): def __init__(self): super()
As you can see, this is the basic setup of single inheritance.
We can see the base or parent class (also sometimes called the superclass) and derived class or subclass, but we still need to initialize the parent or base class within the subclass or derived or child.
We can call the super() function to make the process more accessible.
The super() function aims to provide a much more abstract and portable solution for initializing classes.
Example 2
class Computer(): def __init__(self, computer, ram, ssd): self.computer = computer self.ram = ram self.ssd = ssd class Laptop(Computer): def __init__(self, computer, ram, ssd, model): super().__init__(computer, ram, ssd) self.model = model lenovo = Laptop('lenovo', 2, 512, 'l420') print('This computer is:', lenovo.computer) print('This computer has ram of', lenovo.ram) print('This computer has ssd of', lenovo.ssd) print('This computer has this model:', lenovo.model)
Example 3: Method overriding
When you define a parent class method in the child class, this process is called Overriding.
In other words, the child class can override its parent or superclass methods by defining the function with the same name.
However, there are some rules for overriding:
- The name of the method should be the same as its parameters.
- If the superclass method is private (prefixed with double underscores), you can’t override it.
In Python, you can use the super() method for overriding. It has the following syntax.
super(class_name, self).override_method_name()
class base(object): def base_func(self): print('Method of base class') class child(base): def base_func(self): print('Method of child class') super(child, self).base_func() class next_child(child): def base_func(self): print('Method of next_child class') super(next_child, self).base_func() obj = next_child() obj.base_func()
Method of next_child class Method of child class Method of base class
Python super() with __init__()
The super() is a built-in function in Python that allows you to call a method from a parent class. It is commonly used with __init__() to ensure that the initialization code of the parent class is executed before the child class’s initialization code.
Example
class Parent: def __init__(self): print("Parent __init__ called") class Child(Parent): def __init__(self): print("Child __init__ called") super().__init__() child_instance = Child()
In this code example, we have two classes, Parent and Child. The Child class inherits from the Parent class.
We want to ensure that the __init__() method of the Parent class is called when we create an instance of the Child class.
When we create an instance of the Child class, the output will be:
Child __init__ called Parent __init__ called
This is because of the super().__init__() call in the Child class’s __init__() method ensures that the __init__() method of the Parent class is called after the “Child init called” print statement.
You can also use super() with __init__() when passing arguments to the parent class’s __init__() method:
class Parent: def __init__(self, name): self.name = name print(f"Parent __init__ called with name: self.name>") class Child(Parent): def __init__(self, name, age): self.age = age print(f"Child __init__ called with age: ") super().__init__(name) child_instance = Child("Alice", 10)
In this example, the Parent class’s __init__() method takes a name argument, and the Child class’s __init__() method takes both name and age arguments. When calling super().__init__(name) in the Child class, we’re passing the name argument to the Parent class’s __init__() method.
Super() function with Multiple Inheritances
In the case of multiple inheritance, the super() function follows the Method Resolution Order (MRO). The MRO dictates the order in which parent classes are traversed when searching for a method.
In Python, the MRO follows the C3 linearization or just “C3,” which guarantees that a class always precedes its parents and a parent precedes its other parent based on their order in the list of base classes.
Example
class A: def __init__(self): print("Initializing A") class B(A): def __init__(self): print("Initializing B") super().__init__() class C(A): def __init__(self): print("Initializing C") super().__init__() class D(B, C): def __init__(self): print("Initializing D") super().__init__() d = D()
Initializing D Initializing B Initializing C Initializing A
Super() function with Multi-Level Inheritance
In the case of multi-level inheritance (i.e., when a subclass inherits from a class that itself inherits from another class), the super() function can be used to call methods from any level in the inheritance hierarchy.
Example
class A: def __init__(self): print("Initializing A") class B(A): def __init__(self): print("Initializing B") super().__init__() class C(B): def __init__(self): print("Initializing C") super().__init__() c = C()
Initializing C Initializing B Initializing A
Python Multiple Inheritance and MRO
Multiple inheritance in Python is when a class can inherit from multiple parent classes. This allows the child class to have attributes and methods from all the parent classes.
However, multiple inheritance can lead to a method being defined in more than one superclass. To handle this, Python uses a rule known as the Method Resolution Order (MRO). The MRO determines the order in which the base classes are searched when executing a method.
Python uses a principle called C3 linearization, or just “C3”, to compute the MRO.
Example
class A: def who_am_i(self): return "A" class B(A): def who_am_i(self): return "B" class C(A): def who_am_i(self): return "C" class D(B, C): pass d = D() print(d.who_am_i())
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Create a Parent Class
Any class can be a parent class, so the syntax is the same as creating any other class:
Example
Create a class named Person , with firstname and lastname properties, and a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person(«John», «Doe»)
x.printname()
Create a Child Class
To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:
Example
Create a class named Student , which will inherit the properties and methods from the Person class:
Note: Use the pass keyword when you do not want to add any other properties or methods to the class.
Now the Student class has the same properties and methods as the Person class.
Example
Use the Student class to create an object, and then execute the printname method:
Add the __init__() Function
So far we have created a child class that inherits the properties and methods from its parent.
We want to add the __init__() function to the child class (instead of the pass keyword).
Note: The __init__() function is called automatically every time the class is being used to create a new object.
Example
Add the __init__() function to the Student class:
When you add the __init__() function, the child class will no longer inherit the parent’s __init__() function.
Note: The child’s __init__() function overrides the inheritance of the parent’s __init__() function.
To keep the inheritance of the parent’s __init__() function, add a call to the parent’s __init__() function:
Example
Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to add functionality in the __init__() function.
Use the super() Function
Python also has a super() function that will make the child class inherit all the methods and properties from its parent:
Example
By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.
Add Properties
Example
Add a property called graduationyear to the Student class:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
In the example below, the year 2019 should be a variable, and passed into the Student class when creating student objects. To do so, add another parameter in the __init__() function:
Example
Add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student(«Mike», «Olsen», 2019)
Add Methods
Example
Add a method called welcome to the Student class:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print(«Welcome», self.firstname, self.lastname, «to the class of», self.graduationyear)
If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.