Inheritance
Inheritance
Sometimes classes are similar.
Instead of repeating the same code, one class can inherit from another class.
This is called inheritance.
What Is Inheritance?
Inheritance means a new class can use code from an existing class.
The existing class is called:
- parent class
- base class
The new class is called:
- child class
- derived class
Why Inheritance Matters
It helps you:
- reuse code
- reduce repetition
- organize related classes
- build larger programs
Real Example
A dog and cat are both animals.
Both may have:
- name
- eat()
But each can also have unique actions.
Parent Class
class Animal:
def eat(self):
print("Eating")
Child Class
class Dog(Animal):
pass
pet = Dog()
pet.eat()
Output
Eating
Dog inherited eat() from Animal.
Add New Child Method
class Animal:
def eat(self):
print("Eating")
class Dog(Animal):
def bark(self):
print("Woof")
pet = Dog()
pet.eat()
pet.bark()
Output
Eating
Woof
Another Example
class Vehicle:
def start(self):
print("Started")
class Car(Vehicle):
def drive(self):
print("Driving")
car = Car()
car.start()
car.drive()
Output
Started
Driving
Inheriting init()
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
pass
tom = Student("Tom")
print(tom.name)
Output
Tom
Why This Is Powerful
You write common code once in the parent class.
Children reuse it.
Code Along
Create a class Device with method power_on().
Create child class Phone.
Run the inherited method.
Mini Challenge
Create:
-
Parent class
Employee- method
work()
- method
-
Child class
Manager- method
lead()
- method
Create one manager object and run both methods.
Expected output:
Working
Leading
Real World Use Case
Apps use inheritance for users/admins, vehicles/cars, employees/managers, enemies/bosses, and UI components.
Quiz
- What is inheritance?
- What is a parent class?
- What is a child class?
- Why is inheritance useful?
Assignment
Create a parent class Animal with method sleep(). Create child class Cat.
Summary
You learned how child classes inherit code from parent classes to reduce repetition and organize programs.