How to access a super class variable in child class in Python
In this tutorial, we will discuss how to access a superclass variable in a child class in Python which comes under the OOPS concept of inheritance. We need to use the variable of any superclass. For example, there is a class named Vehicle which has a variable, namely, fuel, and its child class Car has a variable named no_of_tyres
. Its child class, Swift has a variable named color and we need to access the first variable in our child class which is a car. Here we have discussed something about our task and now we will implement it to understand it in a better way.
It is frequently used whenever OOPS concept comes into effect and it uses inheritance. The classes created once, declared with their variables and methods need not to be defined again in its child class. So we should have a proper understanding of inheritance, super class and its variables and child class which inherits the variables from the super class. We have an example to depict how to use one variable from the super class in its child class.
Access a superclass variable in Python
Here we will discuss how to access a superclass variable in Python, which uses the super()
function that creates a temporary superclass object and allows the use of its methods and attributes. So we have a superclass named Vehicle, and a child class, Car which inherits from its superclass, and a class named Swift which inherits from Car. We will print the variable no_of_tyres
in its child class Swift.
class Vehicle: def __init__(self): self.fuel="Petrol" class Car(Vehicle): def __init__(self): self.no_of_tyres = 4 super().__init__() print(self.fuel) class Swift(Car): def __init__(self): self.color= "White" super().__init__() print(self.no_of_tyres) child_obj = Swift()
Petrol 4
Here we can see a base-class Vehicle that has a child-class Car and which has a child-class, Swift, and we have inherited the variable no_of_tyres in Swift from Car and fuel from its base class Vehicle.
So we have demonstrated the task to access the variable from the super class in Child class.
Thanks for reading the tutorial! I hope you find it useful.
Leave a Reply