Inheritance in Python

This post is lesson 34 of 54 in the subject Python Programming Language

1. Inheritance in Python

Inheritance is one of the important features of object-oriented programming. This feature refers to defining a new class based on an existing class. The new class is called the derived class or child class, while the old class is called the base class or parent class.

1.1. Child class and parent class in Python

Python is also an object-oriented programming language, so it also supports inheritance. Any class in Python can also be a base class. The syntax of inheritance in Python is:

class BaseClass:
  # Body of base class
class DerivedClass(BaseClass):
  # Body of derived class

DerivedClass will inherit the attributes and methods from BaseClass. The purpose of this is to reuse code. Additionally, DerivedClass can define its attributes and methods.

An example of creating a parent class Person

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def info(self):
    print(self.name + ",", self.age, "years old.")

# create objects of Person class
john = Person("John", 36)
john.info()
marry = Person("Marry", 35)
marry.info()

An example of the child class “Student” inherits from the parent class “Person”

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def info(self):
    print(self.name + ",", self.age, "years old.")

# Student inherits from Person
# without add any other properties or methods
class Student(Person):
  pass

# create an object of Student class
kane = Student("Kane", 29)
kane.info()

Result

Kane, 29 years old.

In the example given, the class Student inherits the class Person without adding any properties or methods of its own. This means that the Student class has the same attributes and methods as the Person class.

In some instances, the child class may not have anything defined, as is the case with the Student class. Whenever you create an object of the Student class, Python will automatically invoke the __init__() function of the Person class that the Student class is derived from.

1.2. Define the init() function in the child class

We can redefine the initialization function __init__() in the child class. At this point, the __init__() function in the child class will override the function inherited from the parent class.

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def info(self):
    print(self.name + ",", self.age, "years old.")

# Student inherits from Person
class Student(Person):
  def __init__(self, name, age):
    Person.__init__(name, age)

In the example above, we call the __init__() function of the Person class in the Student class to ensure inheritance. If we don’t use Person.__init__(name, age), we can use super().__init__(name, age).

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def info(self):
    print(self.name + ",", self.age, "years old.")

# Student inherits from Person
class Student(Person):
  def __init__(self, name, age):
    super().__init__(name, age)

The super() function helps the child class automatically inherit attributes and methods from the parent class.

1.3. The child class has its attributes and methods

The child class usually has its attributes and methods.

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def info(self):
    print(self.name + ",", self.age, "years old.")

# Student inherits from Person
class Student(Person):
  def __init__(self, name, age, id):
    super().__init__(name, age)
    self.id = id

  def infoStudent(self):
    print(self.name + ",", self.age, "years old, id:", self.id)

son = Student("Son", 30, "0469191517")
son.infoStudent()

Result

Son, 30 years old, id: 0469191517

In the example above, the Student class inherits from the Person class. And the Student class added the attribute id and the method infoStudent().

2. Method overriding in Python

The child class can redefine the methods inherited from the parent class. This is called method overriding.

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def info(self):
    print(self.name + ",", self.age, "years old.")

# Student inherits from Person
class Student(Person):
  def __init__(self, name, age, id):
    super().__init__(name, age)
    self.id = id

  def info(self):
    print(self.name + ",", self.age, "years old, id:", self.id)

son = Student("Son", 30, "0469191517")
son.info()

Result

Son, 30 years old, id: 0469191517

In the example above, the Student class inherits the info() method from the Person class. And the Student class has redefined the info() method for itself.

3. Using isinstance() and issubclass() functions in Python

The isinstance() function helps to check if an object is an instance of a class or not. The issubclass() function helps to check if a class is a subclass of another class or not. And the type() function returns the data type of a variable in Python.

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def info(self):
    print(self.name + ",", self.age, "years old.")

# Student inherits from Person
class Student(Person):
  def __init__(self, name, age, id):
    super().__init__(name, age)
    self.id = id

  def info(self):
    print(self.name + ",", self.age, "years old, id:", self.id)

# check subclass
print("Is Student subclass of Person?", issubclass(Student, Person))
print("Is Person subclass of Student?", issubclass(Person, Student))
print("\n")
# create objects
kane = Person("Kane", 29)
print("Is kane an instance of Person?", isinstance(kane, Person))
print("Is kane an instance of Student?", isinstance(kane, Student))
son = Student("Son", 30, "0469191517")
print("Is son an instance of Person?", isinstance(son, Person))
print("Is son an instance of Student?", isinstance(son, Student))
print("\n")
# type of kane and son
print("Type of kane:", type(kane))
print("Type of son:", type(son))

Result

Is Student subclass of Person? True
Is Person subclass of Student? False

Is kane an instance of Person? True
Is kane an instance of Student? False
Is son an instance of Person? True
Is son an instance of Student? True

Type of kane: <class '__main__.Person'>
Type of son: <class '__main__.Student'>

We see that the Student class inherits from the Person class. Therefore, objects of the Student class are also objects of Person. Objects of Person are not objects of Student.

5/5 - (1 vote)
Previous and next lesson in subject<< The __init__() constructor function of a class in PythonMultiple Inheritance in Python >>

Leave a Reply

Your email address will not be published. Required fields are marked *