Python call super method

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.

Читайте также:  Pdf about html code

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)

Python Super Function Example

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:

  1. The name of the method should be the same as its parameters.
  2. 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())

Источник

super in python

Python Certification Course: Master the essentials

The super function in Python is used to access methods of the immediate parent class.

Syntax of super() in Python

The syntax of super in python is given below:

Parameters of super() in Python

The super function in Python takes two optional parameters:

  • ClassName : This is the name of the subclass.
  • ClassObject : This is an object of the subclass.

Return Values of super() in Python

Return Type:

The super in Python returns a temporary proxy object of the immediate parent class that can be used to call methods of the parent class.

Example of super() in Python

Let’s understand the super in python using an example.

What is super() Function in Python?

For understanding the super function, one should be familiar with the concept of classes and inheritance in Python.

Inheritance is a mechanism by which a class derives (or inherits) attributes and behaviors from another class without needing to implement them again.

Sub and Super class in python

Now, getting back to super. When do we use it?

Super is used when we need to build classes that extend the functionality of previously built classes. Let’s understand this with an example.

Square has a side attribute and one method for calculating area.

Now, we will create a class Cube that inherits Square . With the help of super we can implement the surface_area method in Cube without having to re-write the method for calculating area:

To summarise, super() returns a temporary object of the superclass that then allows us to call that superclass’s methods.

Use of super() in Python

The benefits of using a super function are:

  • No need to specify the parent class name.
  • Helps in implementing modularity (isolating changes) and code reusability.

More Examples

Example 1: super() with Single Inheritance

Let’s understand the use of the super() function in the single inheritance ie IS-A relationship. Till now, we have understood that the super() function is used to access the members of the immediate parent’s class.

Let’s understand how to call the parent’s class method using the super() function in the single Inheritance.

In the below example, the dog class is inheriting the Animal class. This is an example of single-level inheritance. If we want to access the method of the animal class in the dog class, we can access them using the super() method.

Let’s understand how to use super with single inheritance.

The super().smell() is calling the method of the parent’s class method.

Example 2: super() with Multiple Inheritance

In multiple inheritance, a particular class can inherit as many classes.

Let’s understand multiple inheritance using an example.

In the below example, the Child is inheriting two classes.

Now, how to access the constructor of the Parent class using the super() function? First of all, we have to understand the concept of the MRO.

MRO

MRO stands for Method Resolution Order. MRO defines the order of the inherited methods in the child class. Let’s understand using the above example, In the above example we are accessing the constructor using the super() function, the super() will search the constructor according to the order of the inherited class, it will search first in the Parent1 class than in the Parent class.

In the above case, the constructor is already present in the Parent1 class that’s why the constructor of the Parent1 class is executed instead of the Parent class, and also the super() function in python is used to access the immediate parent’s class members.

Let’s understand this using an example.

Let’s understand the order of inheriting class by the Child class.

We can see clearly in the output, the Child class first extends the Parent1 class then extend the Parent class. The object class is the super class of all the classes in the python language that’s why at last the Child class also extends the object class by default.

Now how to access the method of the Parent class using the super function? Let’s understand the syntax of the super() function to access the Parent class methods using the super() function.

This super() function accepts two parameters in the multiple inheritance.

  • ImmediateClassName: The name of the class that is just inherited before the class that we want to access using the super() function.
  • currentObject: The current object of the class.

Let’s understand how to access the constructor of the Parent class from the Child class.

The constructor of the Parent class is accessed using the super() function in the Child class.

Conclusion

  • The super function in Python is used to access methods of the immediate parent class.
  • The Return type of the Super function is a proxy object of the Immediate class.
  • The super() function use the concept of MRO in the multiple inheritance.
  • The super() function also takes two parameters i.e the immediate parent class name and the current object.

See Also:

Источник

Оцените статью