Explore Class Inheritance
In this step, you will learn about class inheritance, a fundamental concept in object-oriented programming (OOP). Inheritance allows you to create new classes (child classes) that inherit attributes and methods from existing classes (parent classes). This promotes code reuse and helps in building more organized and maintainable code.
Let's start by creating a simple parent class called Animal
:
## Create a file named animal.py in the ~/project directory
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Generic animal sound")
Open your VS Code editor and create a new file named animal.py
in the ~/project
directory. Copy and paste the above code into the file. This class has an __init__
method (constructor) that initializes the name
attribute and a speak
method that prints a generic animal sound.
Now, let's create a child class called Dog
that inherits from the Animal
class:
## Add the following code to animal.py
class Dog(Animal):
def speak(self):
print("Woof!")
Add the above code to the animal.py
file. The Dog
class inherits from Animal
by specifying Animal
in parentheses after the class name. The Dog
class also overrides the speak
method to provide its own specific implementation.
Next, let's create another child class called Cat
that also inherits from the Animal
class:
## Add the following code to animal.py
class Cat(Animal):
def speak(self):
print("Meow!")
Add the above code to the animal.py
file. The Cat
class also inherits from Animal
and overrides the speak
method.
Now, let's create a main program to use these classes:
## Create a file named main.py in the ~/project directory
from animal import Animal, Dog, Cat
animal = Animal("Generic Animal")
dog = Dog("Buddy")
cat = Cat("Whiskers")
animal.speak()
dog.speak()
cat.speak()
Create a new file named main.py
in the ~/project
directory and copy and paste the above code into the file. This program imports the Animal
, Dog
, and Cat
classes from the animal.py
file. It then creates instances of each class and calls their speak
methods.
To run the program, open your terminal in VS Code and navigate to the ~/project
directory:
cd ~/project
Then, execute the main.py
script using the python command:
python main.py
You should see the following output:
Generic animal sound
Woof!
Meow!
This demonstrates how the Dog
and Cat
classes inherit from the Animal
class and provide their own specific implementations of the speak
method. This is a basic example of class inheritance in Python.