Inheritance (Inheritance) in Python

Inheriting in object-oriented programming allows us to declare new classes to re-use the parent class's functions and attributes and extra functions. In this article, we will learn how to use legacy in Python.

What is inheritance?

Inheritance allows a class (class) to inherit properties and methods from other defined classes. The class has been called a parent class (base class or parent class), the newly derived class is called a subclass (child class or derived class). The subclass inherits all elements of the superclass, which can extend inheritance elements and add new components.

Syntax of inheritance

 class BaseClass: 
Body of base class

class DerivedClass(BaseClass):
Body of derived class

For more clarity about using inheritance, let's take an example.

Polygon is a closed shape with 3 or more sides. We have a class called DaGiac defined as follows.

 class DaGiac: 

def __init__(self, socanh):
self.n = socanh
self.canh = [0 for i in range(socanh)]

def nhapcanh(self):
self.canh = [float(input("Bạn hãy nhập giá trị cạnh "+str(i+1)+" : ")) for i in range(self.n)]

def hienthicanh(self):
for i in range(self.n):
print("Giá trị cạnh",i+1,"là",self.canh[i])

Class DaGiac has the n attribute to define the number of edges and edges to store each edge value. The nhapcanh () function takes the size of the edges and hienthicanh () will display the list of polygons.

The triangle is polygon with three sides, so we will create a class TamGiac inherited from DaGiac. This new class will inherit all the properties available in the superclass, so you won't need to re-declare (reuse code). This TamGiac is declared as follows:

 class TamGiac(DaGiac): 

def __init__(self):
DaGiac.__init__(self,3)

def dientich(self):
a, b, c = self.canh
# Tính nửa chu vi
s = (a + b + c) / 2
area = (s*(sa)*(sb)*(sc)) ** 0.5
print('Diện tích của hình tam giác là %0.2f' %area)

The TamGiac class not only inherits but also defines a new function as the dientich function .

 >>> t = TamGiac() 
>>> t.nhapcanh()
Bạn hãy nhập giá trị cạnh 1 : 3
Bạn hãy nhập giá trị cạnh 2 : 5
Bạn hãy nhập giá trị cạnh 3 : 4

>>> t.hienthicanh()
Giá trị cạnh 1 là 3.0
Giá trị cạnh 2 là 5.0
Giá trị cạnh 3 là 4.0

>>> t.dientich()
Diện tích của hình tam giác là 6.00

We can see that the functions nhapcanh (), hienthicanh () are not in TamGiac class, but we still use them

Overriding in Python

Python allows to override parent class methods. You can perform the override of the parent class method if you want to have special or special features in the subclass.

In the above example, we see that the TamGiac class uses the __init __ () function from the DaGiac class , if you want to override the definition of __init __ () function in the parent class, we use the super () function.

super () .__ init __ (3) is equivalent to DaGiac .__ init __ (self, 3)

Also Python has two isinstance () and issubclass () functions that are used to test the relationship of two classes and instances.

The issubclass function (classA, classB) returns True if class A is a subclass of class B.

 >>> issubclass(DaGiac,TamGiac) 
False

>>> issubclass(TamGiac,DaGiac)
True

>>> issubclass(bool,int)
True

The isinstance (obj, Class) function returns True if obj is an instance of Class or is an instance of Class's subclass.

 >>> isinstance(t,TamGiac) 
True

>>> isinstance(t,DaGiac)
True

>>> isinstance(t,int)
False

>>> isinstance(t,object)
True

See more:

  1. Object-oriented programming in Python
  2. Manage files and folders in Python
  3. Learn about Error and Exception

Previous lesson: Class and Object in Python

Previous article: Multiple Inheritance in Python

5 ★ | 1 Vote

May be interested

  • Multiple choice quiz about Python - Part 3Multiple choice quiz about Python - Part 3
    today's topic quantrimang wants to challenge you is about file and exception handling in python. let's try the following 15 questions!
  • 5 choose the best Python IDE for you5 choose the best Python IDE for you
    in order to learn well python, it is essential that you find yourself an appropriate ide to develop. quantrimang would like to introduce some of the best environments to help improve your productivity.
  • What is Python? Why choose Python?What is Python?  Why choose Python?
    python is a powerful, high-level, object-oriented programming language, created by guido van rossum. python is easy to learn and emerging as one of the best introductory programming languages ​​for people who are first exposed to programming languages.
  • Module time in PythonModule time in Python
    python has a time module used to handle time-related tasks. tipsmake.com will work with you to find out the details and functions related to the time specified in this module. let's follow it!
  • Python data type: string, number, list, tuple, set and dictionaryPython data type: string, number, list, tuple, set and dictionary
    in this section, you'll learn how to use python as a computer, grasp python's data types and take the first step towards python programming.
  • How to install Python on Windows, macOS, LinuxHow to install Python on Windows, macOS, Linux
    to get started with python, you first need to install python on the computer you are using, be it windows, macos or linux. below is a guide to installing python on your computer, specific to each operating system.
  • How to set up Python to program on WSLHow to set up Python to program on WSL
    get started with cross-platform python programming by setting up python on the windows subsystem for linux. here's how to set up python for wsl programming.
  • Multiple choice quiz about Python - Part 4Multiple choice quiz about Python - Part 4
    continue python's thematic quiz, part 4 goes back to the topic core data type - standard data types in python. let's try with quantrimang to try the 10 questions below.
  • How to use Closure in PythonHow to use Closure in Python
    in this article, tipsmake.com will work with you to learn about closure in python, how to define a closure and why you should use it. let's go find the answer!
  • Functions in PythonFunctions in Python
    what is python function? how is the syntax, components, and function types in python? how to create functions in python? these questions will be answered in the python lesson below.