Min menu

Pages

Inheritance in Python

  Inheritance in Python

Inheritance in Python, to begin with, the word inherit means to include the content of one class in another class.
In Python, a class can inherit from another class to get the functions and variables in it.


So the idea of ​​inheritance is simple, but its utility is very powerful. For example, if you want to create a new class and notice that there is a ready-made class that contains codes that may be useful to you, you can use them instead of writing them from scratch, that is, you can make the class that you defined inherit this class, and then you can use all the variables and functions that the new class inherited from the class ready made.


To make a class inherit from another class, we put in parentheses after the class name and inside them the name of the class we want it to inherit from.
In the event that a class inherits from more than one class, a comma must be placed between each of the two classes that we put between the parentheses.


Technical Terms About Inheritance in Python

  • heredity is calledInheritancein English.

  • The class that inherits from another class is called the son class, and it is calledSubclassAnd it is also called(Derived Class,Extended ClassorChild Class).

  • The class that bequeaths its contents to another class is called the father class, and it is calledSuperclassAnd it is also called(Base ClassorParent Class).


Whatch out  

theSubclassinherit everything present intheSuperclassDirectly, except for the properties that are defined as parameters inside the function __init__(), and the reason for this is that this function generates the properties of the object and associates them with the class at the moment the object is created.
That is, if you do not create an object from the class, this function will not be called in the first place, and therefore it is not considered as properties that exist directly in the class itself.

If you want to call the function __init__()intheSuperclassWe use a ready-made function calledsuper().
Do not worry if you do not understand everything we have mentioned now because you will understand all these things in detail from examples. And the function super()we will explain in detail in the next lesson.

Forms of inheritance in   Python

In Python there are 4 forms of inheritance as shown in the following table.

Inheritance forms in Python

The forms of inheritance in Python are as follows:

  • Single Inheritance: It means a class that inherits from only one class.

  • Successive Inheritance: It means a class that inherits from one class, and this class was originally inherited from another class.

  • Hierarchical inheritance: means that a class is inherited by more than one class.

  • Multiple inheritance: means that a class inherits from more than one class.

 Examples of Inheritance Forms in Python

In all the examples we will assume that each class is defined inside a special file as developers do in real life.


Example of single inheritance in Python 

In the following example, we have defined a class whose name Acontains a variable named xand a function namedprint_msg().
Then we created a class named Bit contains a variable named yand inherits from the classA.

The form of inheritance will be as follows.

Example of haploid inheritance

First example using single inheritance 

A.py
# print_msg and a function named x contains a variable named A here we have defined a class named
		  class A:
	  
		  x = 10
	  
		  def print_msg(self):
		  print('Hello from class A')
	

B.py
# So that we can inherit from A.py which is in file A here we have included the class
		  from A import A
	  
	  
		  # y contains a variable named A that inherits from class B. Here we have defined a class named
		  class B(A):
	  
		  y = 20
	

Test.py
# So that we can create an object from B.py which is in file B here we have included the class
		  from B import B
	  
	  
		  #B Here we have created an object from the class
		  b = B()
	  
		  # B which is defined in class b in object y here we print the value of the variable
		  print('y:', by)
	  
		  # A from class B inherited from class b in object x here we print the value of the variable
		  print('x:', bx)
	  
		  # A from class B inherited from class b in the print_msg() object here we called the function
		  b.print_msg()
	

We will get the following result when we run the fileTest.

y: 20
x: 10
Hello from class A


Example of  Cascading Inheritance in Python 

In the following example, we have defined a class whose name Acontains a function whose name isprint_a().
Then we created a class whose name Bcontains a function whose name print_b()it inherits from the classA.
Then we created a class whose name Ccontains a function whose name print_c()it inherits from the classB.

The form of inheritance will be as follows.

Example of successive inheritance

Second example using Cascading Inheritance in Python

A.py
# print_a contains a function named A. Here we have defined a class whose name is
		  class A:
	  
		  def print_a(self):
		  print('Hello from class A')
	

B.py
# So that we can inherit from A.py which is in file A here we have included the class
		  from A import A
	  
	  
		  # print_b and contains a function named A that inherits from class B. Here we have defined a class named
		  class B(A):
	  
		  def print_b(self):
		  print('Hello from class B')
	

C.py
# So that we can inherit from B.py which is in file B here we have included the class
		  from B import B
	  
	  
		  # print_c contains a function named B that inherits from class C. Here we have defined a class named
		  class C(B):
	  
		  def print_c(self):
		  print('Hello from class C')
	

Test.py
# So that we can create an object out of C.py which is in the C file here we have included the class
		  from C import C
	  
	  
		  C# Here we have created an object from the class
		  c = C()
	  
		  # c Here we have called all the functions in the object
		  c.print_a()
		  c.print_b()
		  c.print_c()
	

We will get the following result when we run the fileTest.

Hello from class A
Hello from class B
Hello from class C


Example of Multiple Inheritance in Python

In the following example, we have defined a class whose name Acontains a function whose name isprint_a().
Then we created a class named after Ba function namedprint_b().
Then we created a class whose name Ccontains a function whose name print_c()it inherits from the class Aand the classB.

The form of inheritance will be as follows.

Example of multiple inheritance

Third example using multiple inheritance in Python

A.py
# print_a contains a function named A. Here we have defined a class whose name is
		  class A:
	  
		  def print_a(self):
		  print('Hello from class A')
	

B.py
# print_b contains a function named B. Here we have defined a class whose name is
		  class B:
	  
		  def print_b(self):
		  print('Hello from class B')
	

C.py
# So that we can inherit from them B.py which is in file B and the class A.py which is in file A here we have included the class
		  from A import A
		  from B import B
	  
	  
		  # print_c contains a function named B, and class A inherits from class C. Here we have defined a class named
		  class C(A, B):
	  
		  def print_c(self):
		  print('Hello from class C')
	

Test.py
# So that we can create an object out of C.py which is in the C file here we have included the class
		  from C import C
	  
	  
		  C# Here we have created an object from the class
		  c = C()
	  
		  # c Here we have called all the functions in the object
		  c.print_a()
		  c.print_b()
		  c.print_c()
	

We will get the following result when we run the fileTest.

Hello from class A
Hello from class B
Hello from class C


Example of hierarchical inheritance in Python

In the following example, we have defined a class whose name Acontains a function whose name isprint_a().
Then we created a class whose name Bcontains a function whose name print_b()it inherits from the classA.
Then we created a class whose name Ccontains a function whose name is also print_c()inherited from the class A.

The form of inheritance will be as follows.

An example of hierarchical inheritance

Fourth example using hierarchical inheritance in Python

A.py
# print_a contains a function named A. Here we have defined a class whose name is
		  class A:
	  
		  def print_a(self):
		  print('Hello from class A')
	

B.py
# So that we can inherit from A.py which is in file A here we have included the class
		  from A import A
	  
	  
		  # print_b and contains a function named A that inherits from class B. Here we have defined a class named
		  class B(A):
	  
		  def print_b(self):
		  print('Hello from class B')
	

C.py
# So that we can inherit from A.py which is in file A here we have included the class
		  from A import A
	  
	  
		  # print_c and contains a function named A that inherits from class C. Here we have defined a class named
		  class C(A):
	  
		  def print_c(self):
		  print('Hello from class C')
	

Test.py
# So that we can create objects from C.py in file C and B.py class in file B here we have included the class
		  from B import B
		  from C import C
	  
	  
		  # and call all the functions in it C here we have created an object of the class
		  c = C()
		  c.print_a()
		  c.print_c()
	  
		  # and call all the functions in it B here we created an object of the class
		  b = B()
		  b.print_a()
		  b.print_b()
	

We will get the following result when we run the fileTest.

Hello from class A
Hello from class B
Hello from class A
Hello from class C

Name collision when inheriting more than one class in Python

When a class inherits more than one class, there is a high probability that it will inherit properties and functions that have the same name and thus a name conflict will occur.
Now you have to know that the name collision does not cause an error in the code when running, but it may lead to a logical error in the desired result.


Important information about name collision when inheriting more than one class

If the class inherits from two classes, and in both of them there is a variable with the same name and a function that has the same name, the Python interpreter will inherit the variable and the function in the first class to inherit from. Because the first class to be inherited is given priority to execute in the event of a name collision.


In the following example, we have defined a class whose name Acontains a function whose name isprint_msg().
Then we created a class whose name Bcontains a function named print_msg()as well.
Then we created a class whose name Cinherits from the class Aand the class Band contains a function namedcall_print_msg().

So here we have multiple inheritance and its form is as follows.

Name collision when inheriting more than one class in Python

Example 

A.py
# print_msg contains a function named A. Here we have defined a class whose name is
		  class A:
	  
		  def print_msg(self):
		  print('Hello from class A')
	

B.py
# print_msg contains a function named B. Here we have defined a class whose name is
		  class B:
	  
		  def print_msg(self):
		  print('Hello from class B')
	

C.py
# So that we can inherit from them B.py which is in file B and the class A.py which is in file A here we have included the class
		  from A import A
		  from B import B
	  
	  
		  # call_print_msg contains a function named B, and class A inherits from class C. Here we have defined a class named
		  A # So when any conflict occurs, the thing in class B will be called, and then it inherits from class A, inherits from class C, here we made the class
		  class C(A, B):
	  
		  # A in the print_msg() class will call the call_print_msg() function when the function is called
		  def call_print_msg(self):
		  self.print_msg()
	

Test.py
# So that we can create an object out of C.py which is in the C file here we have included the class
		  from C import C
	  
	  
		  C# Here we have created an object from the class
		  c = C()
	  
		  # B or in class A in class print_msg() to see if it will execute the function call_print_msg() here we called the function
		  c.call_print_msg()
	

We will get the following result when we run the fileTest.

Hello from class A

Solve the problem of name collision in Python

If you want to create a class and want to ensure that there is no problem with name collision when inheriting this class, you can adopt the principle of data hiding(Data Hiding)When naming variables and functions. So the idea of ​​hiding the data made the programmer able to put the same names of variables and functions in the parent class and the son class, while ensuring that no conflict occurred.

Now, you can simply put the symbol __at the beginning of the variable or function name to be able to use the same name in the class that inherits them.
Then the Python interpreter will differentiate between things in the parent class and things in the son class.


Important information to solve the name collision problem

When you inherit a hidden thing, whether it is a function or a variable, you access it as follows: you put the symbol _ClassName__ItsName
. For example, if you create a class named after Ait and put in it a hidden variable named__x,If you inherit this variable, you can access it as follows_A__x.
So the Python interpreter renames the hidden variable after the name of the class, thus ensuring that no name collision occurs.


In the following example, we have defined a class that inherits from class, and both of them contain a daemon variable named __xand a daemon function named__print_msg().
Then we created an object from the son class in which we displayed the value of all the hidden variables in it and we called the hidden functions as well.

Example 

A.py
# __print_msg and a daemon function named __x contains a daemon named A. Here we have defined a class whose name is
		  class A:
	  
		  __x = 10
	  
		  def __print_msg(self):
		  print('Hello from class A')
	

B.py
# So that we can inherit from A.py which is in file A here we have included the class
		  from A import A
	  
		  # __print_msg and a daemon function named __x and it contains a daemon variable named A, which inherits from class B. Here we have defined a class named
		  class B(A):
	  
		  __x = 20
	  
		  def __print_msg(self):
		  print('Hello from class B')
	

Test.py
# So that we can create an object from B.py which is in file B here we have included the class
		  from B import B
	  
	  
		  C# Here we have created an object from the class
		  b = B()
	  
		  # B in class __x and the value of the variable A in class __x here we have printed the value of the variable
		  print('__x obtained from class A =', b._A__x)
		  print('__x obtained from class B =', b._B__x)
	  
		  # B in the __print_msg() class and function A in the __print_msg() class here we called the function
		  b._A__print_msg()
		  b._B__print_msg()
	

We will get the following result when we run the fileTest.

__x obtained from class A = 10
__x obtained from class B = 20
Hello from class A
Hello from class B

 Classes objectin Python

In Python, any prepared class or you create it yourself automatically inherits from its name classobject.
So, class objectis consideredSuperclassFor all classes in Python.
So any object we create will have all the properties and functions in it.


Now, if we define a class its name Testdoes not inherit from any class.
Be sure that the Python interpreter will make the class Testautomatically inherit from the class objectas follows.

Test(object):
	  

As for the functions that appear to you while writing the code as soon as you put a dot after the name of the object that you did not define yourself, as in the following image.
These functions are found in the object because this object was originally created from a class that inherits from the classobject.



Technical information about the class object 

The class objectis placed inside a module namedbuiltins.py.
This module is automatically included by the Python interpreter in every class, that's why you don't need to do itimport.

You should also know that the module builtins.pycontains all the functions that we used previously, which we used to say were ready-made functions in Python.
It also contains many classes other than the class, objectbut we will not address them in this lesson.


The following table contains the characteristics of the classobject.

The name of the property and its definition
__class__ Returns the name of the class from which the object that called it was created.
__dict__ Returns an object dictwith all the properties of the class from which the object that called it was created.
__doc__ return the explanation(Documentation)The subject in the class from which the object that called it was created.
__module__ Returns the name of the module containing the class from which the object that called it was created.

The following table contains some class functionsobject.

Function name and definition
__init__() This function is used to define properties of an object and give them initial values.
This function is called automatically when an object is created from the class that contains it.
__del__() This function is used to execute certain commands when the object is cleared from memory.
This function is called automatically when an object is deleted from the class that contains it.
__sizeof__() Returns an integer representing the size of the object(what space it occupies)in the memorywithByte.
__repr__() Returns a text representing the shape of the object as it was called in memory, respecting the type and value of the object.
Note: Calling this function is identical to calling a function whose name is repr(object)placed directly in the modulebuiltins.py.
__str__() Returns a text representing the shape of the object as it was called in memory.
Note: Calling this function is identical to calling a function whose name is str(object)placed directly in the modulebuiltins.py.


In the following example, we have defined a class whose name Carwe put the function __init__()and the function in it__del__().
Then we create an object from it and call the properties and functions that the class originally inherited Carfrom the classobject.

first example

Car.py
# Car Here we have defined a class named
		  class car:
		  # ( Documentation ) Here we put an explanation of the class
		  ''This class represent any car object''''
	  
		  # which will be called automatically when the __init__() object is created. Here we have defined the function
		  def __init__(self, model, year, color, price):
		  self.model = model
		  self.year = year
		  self.color = color
		  self.price = price
	  
		  # which will be called automatically when the object is flushed from memory __del__() Here we have defined the function
		  def __del__(self):
		  print('Object is destroyed')
	


Test.py
# So that we can create an object out of Car.py in the Car file here we have included the class
		  from Car import Car
	  
	  
		  # Car Here we have created an object of class
		  obj = Car('BMW', '2015', 'Black', 22000)
	  
		  # object from the Car class inherited by the obj class. Here we have shown some object property values
		  print('Object class name: ', obj.__class__)
		  print('Object module name: ', obj.__module__)
		  print('Object class documentation: ', obj.__doc__)
		  print('Object properties and values:', obj.__dict__)
	  
		  # object of the Car class inherited by the obj class. Here we called some of the object functions
		  print('Object size in Byte: ', obj.__sizeof__())
		  print('Object representation: ', obj.__repr__())
		  print('Object string representation:', obj.__str__())
	  
		  # Automatically __del__() and thus the obj function will be called here we have deleted the object
		  del obj
	

We will get the following result when we run the fileTest.

Object class name: <class 'Car.Car'>
Object module name: Car
Object class documentation: This class represent any car object
Object properties and values: {'model': 'BMW', 'year': '2015', ' color': 'Black', 'price': 22000}
Object size in Byte: 16
Object representation: <Car.Car object at 0x01080A30>
Object string representation: <Car.Car object at 0x01080A30>
Object is destroyed


Now you may be wondering: What is the difference between a function __repr__()and __str__() since you didn't notice any difference between them in the previous example.
The following example shows you the difference between them.

second example

Test.py
# 'Python Tutorial' Here we have created a text object whose value is
		  obj = 'Python Tutorial'
	  
		  # Its value will appear as text __repr__() Note that the function
		  print('Object representation: ', obj.__repr__())
	  
		  # It will only show its value __str__() while the . function
		  print('Object string representation:', obj.__str__())
	

We will get the following result when we run the fileTest.

Object representation: 'Python Tutorial'
Object string representation: Python Tutorial


Know the nature of the relationship between classes and objects in Python

The following table contains ready-made functions in Python that can be used to find out the nature of the relationship between one class and another or between one object and another.
Note:  In the examples topic we used the keyword to define empty classes. So we advise you to look at the examples. pass 

Function name and definition
issubclass(subclass, superclass) It is used to find out whether or not the class we pass in place of the parameter inherits from the class we pass in place of the parameter . Returns if it is, and otherwise returns subclass  superclass 
 True  False.
Explanation of the issubclass() function
isinstance(obj, classinfo) Used to find out if the object we pass in place of the parameter is created from the class we pass in place of the parameter or not. Returns if it is, and otherwise returns obj  classinfo 
 True  False.
Explanation of the function isinstance()

Function Explanation issubclass()

Definition of the issubclass function

It is used to find out whether or not the class we pass in place of the parameter subclassinherits from the class we pass in place of the parameter superclass.
Returns Trueif it is, and otherwise returnsFalse.

Note: If the first class inherits directly or indirectly from the second class, it is considered to be inherited from it.



Build the issubclass . function

                  issubclass(subclass, superclass)
	  


Parameters of the issubclass . function

  • Where the parameter is subclass, we pass the name of the class we want to know if it inherits from the other class.

  • Where the parameter is superclass, we pass the name of the class we want to know if it inherits the other class.



issubclass function return value

Returns Trueif the class we pass in place of the parameter subclassinherits from the class we pass in place of the parametersuperclass.
Otherwise it returns False.



Example in issubclass

Test.py
                    # A Here we have defined an empty class called
		  class A:
		  pass
	  
	  
		  # A is inherited from class B. Here we have defined an empty class named
		  class B(A):
		  pass
	  
	  
		  # B inherits from class C. Here we have defined an empty class named
		  class C(B):
		  pass
	  
	  
		  # Several times to see if the first class we pass to it inherits from the other class and each time we print the result issubclass() here we call the function
		  print('Is B inherit from A:', issubclass(B, A))
		  print('Is C inherit from B:', issubclass(C, B))
		  print('Is C inherit from A:', issubclass(C, A))
		  print('Is A inherit from B:', issubclass(A, B))
		  print('Is A inherit from C:', issubclass(A, C))
	

We will get the following result when running.

Is B inherit from A: True
Is C inherit from B: True
Is C inherit from A: True
Is A inherit from B: False
Is A inherit from C: False

Function Explanation isinstance()

Function definition isinstance()

Used to find out if the object we pass in place of the parameter objis created from the class we pass in place of the parameter classinfoor not.
Returns Trueif it is, and otherwise returnsFalse.

Note: If the object was created directly or indirectly from the class, it is considered to be created from it.



Build function isinstance()

                  isinstance(obj, classinfo)
	  


Function parameters isinstance()

  • The location of the parameter objWe pass the object we want to know if it was created from a class.

  • Parameter location classinfoWe pass the name of the class from which we want to know if the object is created.



function return value isinstance()

Returns Trueif the object we pass in place of the parameter objwas created directly or indirectly from the class we pass in place of the parameterclassinfo.
Otherwise it returns False.



Example of the function isinstance()

Test.py
                    # A Here we have defined an empty class called
		  class A:
		  pass
	  
	  
		  #B Here we have defined an empty class named
		  class B():
		  pass
	  
	  
		  # B inherits from class C. Here we have defined an empty class named
		  class C(B):
		  pass
	  
	  
		  # obj named C here we created an object from the class
		  obj = C()
	  
	  
		  # Generate c multiple times to see which class the isinstance() object is in here we called the function
		  print('Is obj instance of A:', isinstance(obj, A))
		  print('Is obj instance of B:', isinstance(obj, B))
		  print('Is obj instance of C:', isinstance(obj, C))
	

We will get the following result when running.

Is obj instance of A: False
Is obj instance of B: True
Is obj instance of C: True