Introduction
In object-oriented programming, we often find that different classes share common features.
Instead of rewriting the same code again and again, we can use a powerful idea called inheritance.
Inheritance allows:
- One class to reuse the attributes and methods of another
- Code to be organised more logically
- Programs to be easier to extend and maintain
In this lesson, you will learn how:
- A child class can inherit from a parent class
- Shared behaviour can be written once
- Specialised behaviour can be added in child classes
Parent and Child Classes
A parent class (also called a base class) contains general attributes and methods.
A child class (also called a subclass) inherits everything from the parent, and can:
- Use the parent’s methods
- Add new methods
- Override existing methods
Basic Inheritance Syntax
class Parent:
def method(self):
print("This is from the parent")
class Child(Parent):
pass
The key part is:
class Child(Parent):
This tells Python that Child inherits from Parent.
Example: Person and Student
class Person:
def __init__(self, name):
self.name = name
def introduce(self):
print("Hello, my name is", self.name)
class Student(Person):
pass
Even though Student has no code inside it, it still:
- Has a
nameattribute - Can use the
introduce()method
Predict:
Look at the code below. What do you think will be printed?
class Person:
def __init__(self, name):
self.name = name
def introduce(self):
print("Hello, my name is", self.name)
class Student(Person):
pass
student = Student("Alex")
student.introduce()
Think about:
- Where is
introduce()defined? - Does the
Studentclass define it? - Why does the method still work?
Run:
Run the program below to check your prediction.
Investigate:
Child classes can also add their own methods.
Try this:
- Add a method called
study()to theStudentclass - Make it print
"Studying..." - Call the method on the student object
Think about:
- Which methods come from the parent?
- Which methods belong only to the child?
Modify:
The following program is meant to demonstrate inheritance, but it contains an error.
Fix the code so that the student can introduce themselves correctly.
The problem
selfis missing when accessingname