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.

  1. class A:
  2. country = "Italy"

Next, I'll define a derived class B(A).

This subclass adds a new property (region).

  1. class B(A):
  2. 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.

  1. class Person():
  2. '''Class that represents a person.'''
  3. def __init__(self, first_name, last_name):
  4. self.first_name = first_name
  5. self.last_name = last_name
  6. def __str__(self):
  7. 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.

  1. class Student(Person):
  2. '''Class that represents a student.'''
  3. def __init__(self, first_name, last_name, school):
  4. self.school = school
  5. Person.__init__(self, first_name, last_name)
  6. def __str__(self):
  7. 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.

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Python Classes