Python super() Built in Function

The super() function in Python is a built-in function that allows you to access the methods and properties of a parent class from a child class. It can also take optional arguments that specify the subclass and an instance of that subclass.

Here are some examples of using the super() function:

# Example 1: Calling parent constructor from child constructor
class Vehicle:
    def __init__(self):
        print('Vehicle __init__() called')

class Car(Vehicle):
    def __init__(self):
        super().__init__()
# same as Vehicle.__init__(self)
        print('Car __init__() called')

car = Car()

# Output:
# Vehicle __init__() called
# Car __init__() called
# Example 2: Calling parent method from child method

class Animal:
    def sound(self):
        print('Animal sound')

class Dog(Animal):
    def sound(self):
        super().sound()
# same as Animal.sound(self)
        print('Woof woof')

dog = Dog()
dog.sound()

# Output:
# Animal sound
# Woof woof
# Example 3: Using super() with multiple inheritance

class A:
    def hello(self):
        print('Hello from A')

class B(A):
    def hello(self):
        print('Hello from B')
        super().hello()

class C(A):
    def hello(self):
        print('Hello from C')
        super().hello()


class D(B,C):
# order matters!
    def hello(self):
        print('Hello from D')
        super().hello()


d = D()
d.hello()

# Output:
# Hello from D
# Hello from B
# Hello from C
# Hello from A

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python float() Built in Function

Python String encode() Method

Python getattr() Built in Function

Python Use Get Method Over Square Brackets

Python exec() Built in Function