Close
Close

Python Subclass of a class


Till now, you have learned about classes and objects. In this chapter, you will learn a new concept of object oriented programming- Subclass.

Python Subclass


To understand what a subclass is, let’s look at an example.

Suppose we define a rectangle with some length and breadth. Now, a square is also a rectangle but having the same length and breadth.

From this, you must have got the feel that a square is a subclass of rectangle.

Let’s think of some more examples of subclasses. A class ‘Book’ can have ‘ScienceBook’ and ‘MathsBook’ as its subclasses. Another class ‘Animals’ can have ‘Dog’, ‘Cat’ and ‘Goat’ as its subclasses.

The class whose subclass has been made is called a superclass. Other names of superclass are base class or parent class, and other names of subclass are derived class or child class. In our Rectangle example, Rectangle is the superclass and Square is its subclass. The process of creating a subclass of a class is called inheritance.

All the attributes and methods of superclass are inherited by its subclass also. This means that an object of a subclass can access all the attributes and methods of the superclass. Moreover, subclass may have its own attributes or methods in addition to the inherited ones as well. 

Subclass in Python

Let's learn to create a subclass in Python.

# superclass
class Person():
    def display1(self):
        print("This is superclass")
 
# subclass		
class Employee(Person):
    def display2(self):
        print("This is subclass")
		
emp = Employee()  # creating object of subclass
 
emp.display1()
emp.display2()
Output
This is superclass
This is subclass

We created two classes Person and Employee with one method in each class.

class Employee(Person) → It means that the class Employee is inherited from the class Person. In simple words, Employee is a subclass of Person. (An employee is a person)

Since Employee is a subclass of Person, it inherits the method display1() of its superclass. 

emp = Employee → We created an object emp of the class Employee.

emp.display1() → An object of a subclass can access any of the members (attributes or methods) of the superclass, so emp was able to call the method display1() of the parent class Person.

So this was a simple implementation of a subclass. Let’s try something more.

We know that an object of a child class can access the attributes or methods of the parent class. But the reverse is not true, i.e., an object of the parent class can’t access the attributes or methods of the child class.

Let’s see what happens when an object of the class Person tries to access the method of its subclass Employee.

# superclass
class Person():
    def display1(self):
        print("This is superclass")
 
# subclass		
class Employee(Person):
    def display2(self):
        print("This is subclass")
		
p = Person()  # creating object of superclass
 
p.display1()
p.display2()
Output
This is superclass
Traceback (most recent call last):
  File "script.py", line 14, in
    p.display2()
AttributeError: 'Person' object has no attribute 'display2'

We created an object p of the parent class Person. This object called the method display1() successfully which printed a message. But when it tried to call the method display2() of its subclass, we got an error as expected.

Look at the next example.

# superclass
class Person():
    def __init__(self, per_name, per_age):
        self.name = per_name
        self.age = per_age
		
    def display1(self):
        print("In superclass method: name:", self.name, "age:", self.age)
 
# subclass		
class Employee(Person):
    def display2(self):
        print("In subclass method: name:", self.name, "age:", self.age)
		
emp = Employee("John", 20)  # creating object of superclass
 
emp.display1()
emp.display2()
print("Outside both methods: name:", emp.name, "age:", emp.age)
Output
In superclass method: name: John age: 20
In subclass method: name: John age: 20
Outside both methods: name: John age: 20

Let’s try to understand what is happening here.

The class Employee is a subclass of the class Person. Thus, Employee inherits the attributes (name and age), the method (display1()) and the constructor (__init__()) of Person. As a result, these can also be accessed by the objects of the subclass Employee.

Therefore, in the method display2() of the subclass, we have directly accessed the attributes name and age of the parent class.

emp = Employee("John", 20) → An object emp of the subclass Employee is created by passing the values “John” and 20 to the per_name and per_age parameters of the constructor of the parent class (because the subclass has inherited the constructor of the parent class). Thus, in the constructor, the values of the attributes name and age become “John” and 20 respectively for the object emp.

emp.display1() →The object emp calls the display1() method of the parent class.

emp.display2() →The object emp calls the display2() method of its own class.

print("Outside both methods: name:", emp.name, "age:", emp.age) →The object emp was able to access the attributes name and age of the parent class. 

If you have understood this example, that means you have understood the concept of subclasses. Now, let’s look at some more cases.

If both the subclass and the superclass has a constructor, then the object of the subclass is created through the constructor of the subclass.

If a subclass has the __init__() method, then it will not inherit the __init__() method of the superclass. In other words, the  __init__() method of the subclass overrides the  __init__() method of the superclass.

Let’s see an example where both the subclass and the superclass has a constructor.

# superclass
class Person():
    def __init__(self, per_name, per_age):
        self.name = per_name
        self.age = per_age
 
# subclass		
class Employee(Person):
    def __init__(self, emp_name, emp_age, emp_salary):
        self.salary = emp_salary
        Person.__init__(self, emp_name, emp_age)
		
emp = Employee("John", 20, 8000)  # creating object of superclass
 
print("name:", emp.name, "age:", emp.age, "salary:", emp.salary)
Output
name: John age: 20 salary: 8000

We created an object emp of the subclass Employee by passing the values “John”, 20 and 8000 to the emp_name, emp_age and emp_salary parameters of the constructor of the child class (because the child class has a constructor of its own). In this constructor, the value of emp_salary is assigned to the attribute salary of the object emp, and the constructor of the parent class is called by passing emp_name and emp_age as the arguments. In the constructor of the parent class, the attributes name and age becomes “John” and 20 respectively for the object emp.

Note that the constructor of the parent class Person is called from the constructor of the child class by writing Person.__init__(self, emp_name, emp_age).

Let’s see one more example.

# superclass
class Person():
    def __init__(self, per_name, per_age):
        self.name = per_name
        self.age = per_age
	
    def display1(self):
        print("name:", self.name)
        print("age:", self.age)

# subclass		
class Employee(Person):
    def __init__(self, emp_name, emp_age, emp_salary):
        self.salary = emp_salary
        Person.__init__(self, emp_name, emp_age)
	
    def display2(self):
        print("salary:", self.salary)
        Person.display1(self)
		
emp = Employee("John", 20, 8000)  # creating object of superclass

emp.display2()
Output
salary: 8000
name: John
age: 20

You must have understood this program. We are calling the constructor of the parent class Person inside the constructor of the child class by writing Person.__init__(self, emp_name, emp_age) and calling the display1() method of the parent class inside the display2() method of the child class by writing Person.display1(self).

Python super() Function


In the previous example, instead of Person.__init__, we can use the super() function for calling the constructor and methods of the parent class inside the child class. 

The super() function returns a parent class object and can be used to access the attributes or methods of the parent class inside the child class.

Let’s rewrite the last example using super().

# superclass
class Person():
    def __init__(self, per_name, per_age):
        self.name = per_name
        self.age = per_age
	
    def display1(self):
        print("name:", self.name)
        print("age:", self.age)

# subclass		
class Employee(Person):
    def __init__(self, emp_name, emp_age, emp_salary):
        self.salary = emp_salary
        super().__init__(emp_name, emp_age)
	
    def display2(self):
        print("salary:", self.salary)
        super().display1()
		
emp = Employee("John", 20, 8000)  # creating object of subclass

emp.display2()
Output
salary: 8000
name: John
age: 20

In this example, we replaced Person.__init__(self, emp_name, emp_age) by super().__init__(emp_name, emp_age) and Person.display1(self) by super().display1() inside the subclass.

When calling a method using super(), passing self as the first argument is not required.

So, that was all that you needed to know about subclasses. After this chapter, practice questions on this topic to have a good hold over it.

There are two in-built functions in Python, namely isinstance() and issubclass(), which can be used to check the class of an object or the subclass of a class. 

Python isinstance()


This function is used to check if an object is an instance of a particular class. In other words, it checks if an object belongs to a particular class.

# superclass
class Person():
    pass

# subclass		
class Employee(Person):
    pass

per = Person()  # creating object of superclass
emp = Employee()  # creating object of subclass

print(isinstance(per, Person))
print(isinstance(per, Employee))
print(isinstance(emp, Person))
print(isinstance(emp, Employee))
Output
True
False
True
True

Here, per is an object of the superclass Person and emp is an object of the subclass Employee. Therefore, per belongs only to Person, whereas emp belongs to Employee as well as Person.

isinstance(per, Person) checks if the object per belongs to the class Person.

Python issubclass()


This function is used to check whether a class is a subclass of another class.

# superclass
class Person():
    pass

# subclass		
class Employee(Person):
    pass

print(issubclass(Person, Employee))
print(issubclass(Employee, Person))
Output
False
True

issubclass(Person, Employee) checks whether the class Person is a subclass of the class Employee.

Before wrapping up this chapter, let’s look at one more example of subclass.

Square and rectangle example

class Rectangle():
    def __init__(self,leng,br):
        self.length = leng
        self.breadth = br
    '''while calling a method in a class python
    automatically passes an instance( object ) of it.
    so we have to pass sef in area i.e. area(self)'''
    def area(self):
        '''length and breadth are not globally defined.
        So, we have to access them as self.length'''
        return self.length*self.breadth
class Square(Rectangle):
    def __init__(self,side):
        Rectangle.__init__(self,side,side)
        self.side = side
s = Square(4)
print(s.length)
print(s.breadth)
print(s.side)
print(s.area())# It appears as nothing is passed but python will pass an instance of class.
Output
4
4
4
16

There is nothing new in the above code to explain. If you are facing any difficulty, then read the comments inside the code.

You can ask questions in the discussion section anytime and feel free to ask.

To learn from simple videos, you can always look at our Python video course on CodesDope Pro. It has over 500 practice questions and over 20 projects.
Setting goals is the first step in turning the invisible into the visible.
- Tony Robbins


Ask Yours
Post Yours
Doubt? Ask question