The Python super()
is a built-in Python function that returns objects represented in the parent’s class. The super
function in Python is used to call a method in a parent class from a subclass.
The object of the superclass that allows you to call that superclass’s methods.
Python super
The super()
function allows you to access a superclass’s functions if your subclass is descended from it. You can use it to get inherited methods from either the parent class or a child class.
The super
function takes two arguments: the first is the subclass itself, and the second is a string representing the name of the parent class.
Syntax of super() in Python
super([type[, object-or-type]])
Return: Return a proxy object which represents the parent’s class.
The super() method can also take two parameters:
- Subclass
- An object that is an instance of that subclass.
Advantages of super() function in Python
The super()
function allows you to switch between superclasses with little to no code modification, saving you from having to rewrite those methods in your subclass.
It offers a much more flexible and abstract way to initialize classes.
How to call a super() function in Python 3
Create a parent and child class, inherit the parent class to the child class, and then use the super()
method from the child class to use a super() function in Python. First, we will add the super function to a standard class definition.
#test.py class MyParentClass(): def __init__(self): pass class SubClass(MyParentClass): def __init__(self): super()
Simple super Class Example
Let’s create a simple base class and inherit into a child class.
#test.py class Employee(): def __init__(self, name, age): self.name = name self.age = age class Dept(Employee): def __init__(self, name, age, dept_name): super().__init__(name, age) self.dept_name = dept_name emp = Dept('adam', 23, 'IT') print('The name is:', emp.name) print('The age is:', emp.age) print('The dept name is:', emp.dept_name)
In the example above, we defined two classes: an Employee base class and a Dept. derived class.
The base class has two properties that we’ve defined, and the derived class has three.
The derived class has three attributes, two of which are derived from the base class and one of which is an independent feature. The child or derived class also contains a model property. The other two are acquired from a computer of the lowest class.
Because of the super()
function, we can still access all of the properties of the base class even if we simply construct an object of the derived class.
Output:
The name is: adam The age is: 23 The dept name is: IT ** Process exited - Return Code: 0 ** Press Enter to exit terminal