Hi there π I'm a New York City based web developer documenting my journey with React, React Native, and Python for all to see. Please follow my dev.to profile or my twitter for updates and feel free to reach out if you have questions. Thanks for your support!
Today is another article on the concept of Object Oriented Programming in Python.
The fact that a child class can inherit data through variables, and actions through methods, from a parent class is a main reason why OOP is powerful. This is called single inheritance and refers to a direct relationship from parent to child class.
In order for a child component to inherit a parent component's methods, you must first instantiate the child Class with the parent's constructor using the super()
method. For example, let's say a Truck class inherits from a Vehicle class:
class Vehicle:
def __init__(self, color):
self.color = color
def get_color(self):
return self.color
class Truck(Vehicle):
def __init__(self, color, horsepower):
super().__init__(color)
self.horsepower = horsepower
Here we see that we use the super()
method to call the parent's constructor function. But this method is built in. Now let's say we want to get the color of the truck using the parent's get_color()
method. In order to call it, we must use the super()
method again, but this time for a non-built-in method.
class Truck(Vehicle):
def __init__(self, color, horsepower):
super().__init__(color)
self.horsepower = horsepower
def compliment_car(self):
truck_color = super().get_color()
print(f"Hey love that {truck_color} truck you have!")
This is how we can use the parent Vehicle's get_color() method on the child Truck class.
If you like projects like this and want to stay up to date with more, check out my Twitter @stonestwebdev, I follow back! See you tomorrow for another project.
Top comments (0)