Inheritance is an important concept in programming languages. It allows us to define brand new classes that inherit from another class, also known as that class' parent. The child that inherits from another class is called the child class.
Creating a Parent Class
Let's start off by defining our parent class. Let's use a simple example:
We've defined a class named Animal with two parameters, the name and weight.
Creating a Child Class
Now that we have our parent class defined, let's create our child class. Dogs are animals so let's create a class that represents a dog.
PYTHON
classDog(Animal):
def__init__(self, name, weight, breed):
super().__init__(self, name, weight)
self.name = name
self.weight = weight
self.breed = breed
defbark(self):
print("Woof woof! I am a " + self.breed)
A lot is going on here. First you can see the syntax for inheriting from a parent class:
PYTHON
classDog(Animal):
Put the name of the class in parenthesis. Next, you can see the use of super() which simply refers to the parent class.
PYTHON
super().__init__(self, name, weight)
This is simply calling the constructor of the parent class, in our case Animal. This is how we inherit all of the properties and methods in our Dog class.
Now let's create a few animals and dogs and see this in action!
Name: Bob Weight: 3
Name: Cookie Weight: 5
Woof woof! I am a Poodle
Notice what just happened here. Even though we defined Cookie as a Dog instead of an Animal, it was still able to call the print_info() function despite the function not existing in Dog.
Of course, this is because of the power of inheritance. Because of this cool feature, we could then go on to define more animals like cats or birds, have them all inherit common properties and functions, while still having custom things unique to them.
Overriding Methods
One last cool feature of inheritance is the concept of overriding methods. This is creating multiple methods with the same name for the purpose of having the child one run instead of the parent.
Since we defined a function with the same name as the parent, print_info, Python automatically runs the one in the child. Now if you want a parent function to have custom functionality in the child class, you can do that.
Inheritance is a great way to organize your code and keep properties and functions where they belong.