Chapter 15: Building on Blueprints - An Introduction to Inheritance
In the last chapter, you learned how to create a class, which acts as a blueprint for objects. Inheritance is a way to create a new, more specialized class based on an existing one.
Think of it this way: all dogs are animals, but not all animals are dogs. An "animal" is a general category. A "dog" is a more specific type of animal. It has all the general attributes of an animal (it needs to eat, sleep, etc.), but it also has its own unique attributes and behaviors (like barking).
In OOP, this is called the "is-a" relationship. A Dog is an Animal. The Dog class can inherit all the features from the Animal class and then add its own.
This is incredibly useful because it allows you to reuse code. You can write a general class once and then create many specialized versions of it without starting from scratch.
Parent Class (or Superclass): The general class that is being inherited from (e.g.,
Animal).Child Class (or Subclass): The specialized class that inherits from the parent (e.g.,
Dog).
Creating a Child Class
Let's use our Dog class from the previous chapter as our parent class.
# The Parent Class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says: Woof!")
Now, let's create a more specific type of dog, a ServiceDog. A service dog is still a dog, so it should have a name and an age, and it should be able to bark. To show this, we make ServiceDog inherit from Dog.
The syntax is to put the parent class name in parentheses after the child class name.
Output:
Even though we didn't write __init__ or bark in our ServiceDog class, it inherited them directly from Dog.
Customizing the Child Class
The real power of inheritance comes from adding new features or changing existing ones. Let's say a ServiceDog also needs a service_type attribute, like "guide dog" or "therapy dog".
To do this, we give the child class its own __init__ method.
The super() Function
super() FunctionWhen you write an __init__ for a child class, you must first call the __init__ of the parent class to make sure all the parent's attributes are set up correctly. The easiest way to do this is with the super() function. super() refers to the parent class.
Output:
Here, super().__init__(name, age) runs the __init__ method from the Dog class, which sets up self.name and self.age. Then, we add the new attribute, self.service_type.
Adding and Overriding Methods
Adding New Methods
You can add new methods to the child class that don't exist in the parent.
Overriding Parent Methods
What if you want a child class method to behave differently than the parent's version? This is called method overriding. You simply define a method in the child class with the same name as one in the parent class.
Let's say a ServiceDog's bark is more of a focused, single "Woof." to alert its owner.
When bark() is called on a ServiceDog object, Python uses the version in the ServiceDog class. For any other Dog object, it uses the original version.
Summary and What's Next
Inheritance is a fundamental concept of OOP that helps you write cleaner, more organized, and reusable code.
A Child Class inherits attributes and methods from a Parent Class.
The
super()function is used to call the parent class's methods, especially its__init__.You can add new attributes and methods to a child class.
You can override a parent's method by defining a method with the same name in the child class.
You've now seen the core ideas behind OOP. In the next chapter, we'll shift gears and look at how you can use code written by others by learning about modules and the Python Standard Library.
Practice Time!
Using the
Carclass from last chapter's practice, create a child class calledElectricCar.Give the
ElectricCaran additional attribute in its__init__method:battery_capacity(e.g., in kWh). Remember to usesuper().Override the
display_infomethod inElectricCarso that it prints the make, model, year, AND the battery capacity.
Last updated