Subclasses in Python
In Python, a subclass (also known as a derived class) is a class that extends another class, referred to as the base or parent class.
class SubclassName(BaseClass):
code
What’s the purpose of a subclass?
The key benefit of using subclasses is inheritance.
A subclass inherits all the properties of its base class, allowing you to avoid redundant code and streamline your programming.
A Practical Example of a Subclass
To illustrate how subclasses work in Python, let’s walk through a simple example.
First, I'll create a base class A() with a single property.
- class A:
- country = "Italy"
Next, I'll define a derived class B(A).
This subclass adds a new property (region).
- class B(A):
- region = "Lazio"
By specifying the base class (A) in parentheses, we indicate that class B automatically inherits all the properties of the base class A.
For example, if I enter the following in the Python interpreter:
B.country
The interpreter retrieves the property from B and outputs:
Italy
Even though the subclass B doesn’t explicitly define this property, it inherits the "country" property from the base class A.
And so forth.
How to Create a Derived Class
This next example is a bit more advanced because it includes methods, but the underlying concept remains consistent.
First, I'll create a base class Person().
Objects belonging to the Person() class have two properties: first name and last name.
- class Person():
- '''Class that represents a person.'''
- def __init__(self, first_name, last_name):
- self.first_name = first_name
- self.last_name = last_name
- def __str__(self):
- return "First Name: " + str(self.first_name) + "\nLast Name: " + str(self.last_name)
Next, I'll create a subclass called Student().
The base class, in this case, is specified in parentheses as Person.
- class Student(Person):
- '''Class that represents a student.'''
- def __init__(self, first_name, last_name, school):
- self.school = school
- Person.__init__(self, first_name, last_name)
- def __str__(self):
- return Person.__str__(self) + "\nSchool: " + str(self.school)
The Student subclass introduces a specific property (school) while inheriting the first_name and last_name properties from the base class Person.
To test this, I'll create an instance of the Student() class:
eric = Student("Eric", "Idle", "British School")
Now, I'll inspect the eric object:
eric
The Python interpreter returns the following information:
First Name: Eric
Last Name: Idle
School: British School
The Student() subclass has inherited the methods of the base class Person().
And so on.