Min menu

Pages

Abstraction in Python

 Abstract concept in Python

Abstraction in Python 

abstraction   (Abstraction)A very important method in programming and it is generally adopted to facilitate writing commands for the programmer and organizing his work, as it makes him able to implement what he wants without having to know all the details in which this was done, and thus making him deal with things superficially instead of diving into knowing the details complex codes.


For example, if you intend to build an application with a user interface and this application contains a specific button, when you click on this button, an email is sent to the owner of the application. In this case, you will not have to worry at all about how the code that allows sending the message will be attached to the button in the user interface, because the developers of the user interface ask you to define a function of a certain shape and put the code to send the message in it, and then pass this function to the object representing the button that appears in the user interface. The code in the function will then be executed each time the button is clicked.


So abstraction is a technique of defining abstract functions(Abstract Methods)In the father's class and forcing the son's class to doOverrideThese functions as appropriate.
Thus, when you create a class that inherits from a class with abstract functions, a warning will appear in front of you telling you that you must doOverridefor these functions so you don't get a runtime error.


Terms about abstraction in Python

  • The ordinary class is calledConcrete Class.

  • The class defined as an abstract class is said to himAbstract Class.

  • The function defined as an abstract function is calledAbstract MethodorFunction Method.

Definition of an abstract class  Abstract Classin python

To convert a regular class to an abstract class, the class must be made to inherit from its name class, which is already ABCpresent in a ready-named module.abc.
Information: The class ABCwas named like this, an acronym for the phrase(A bstract B ase C lasses)Which means the father class of all abstract classes.


Important points about the abstract class in Python 

  • An abstract class can contain normal functions, and it can contain functions of its own kindAbstract.

  • An abstract class cannot create objects from it if it contains functions of its typeAbstract.

  • Since it is not possible to create objects from an abstract class in all cases, this means that the real benefit from this class is its inheritance.

  • A class that inherits from a mere class is obliged to do soOverrideFor all functions defined in itAbstract.



How to define an abstract class in Python

In the following example, we have defined a purely named class ParentClasscontaining a function namedprint_msg.
Then we created a class named ChildClassinherit from the classParentClass.

Note: Classes ChildClassare not obligatoryOverridefor a function print_msg()because it is not defined as an abstract function.

An example showing how to define an abstract class in Python

ParentClass.py
# So that we can inherit from it the abc which is in the ABC module here we have included the class
		  from abc import abc
	  
	  
		  # So that it becomes a simple ABC class and we make it inherit from the ParentClass class, here we create a class named
		  class ParentClass(ABC):
	  
		  # Here we have defined a regular function that prints a sentence when called
		  def print_msg(self):
		  print('Normal method defined in an abstract class')
	

ChildClass.py
# So that we can inherit from it the ParentClass which is in the ParentClass module here we have included the class
		  from ParentClass import ParentClass
	  
	  
		  # ParentClass inherits from the ChildClass class Here we have created an empty class named
		  class ChildClass(ParentClass):
		  pass
	

Test.py
# So that we can create an object from ChildClass here we have included the class
		  from ChildClass import ChildClass
	  
	  
		  # From print_msg() then we called the .obj function named ChildClass here we created an object from the class
		  obj = ChildClass()
		  obj.print_msg()
	

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

Normal method defined in an abstract class

note

In the previous example, you could create an object from a class ParentClassbecause it does not contain abstract functions.
But as we have already said, in general, abstract classes are created in order to be inherited and not in order to create objects from it.


identificationAbstract Methodin python

How to define an abstract class that inherits from an abstract class in Python

If you want to build an empty function and make the class that inherits it forced and responsible for writing its content, put the word @abstractmethodabove it and passjust put the word in it.
And if you want to build a function and make the class that inherits it forced to define it again with the possibility of benefiting from the code in it, @abstractmethodjust put the word above it.


Important points about abstract functions in Python

  • If you put the word @abstractmethodabove the function, it means that it is an abstract function and not a regular function.

  • A class that inherits from a mere class, it must doOverridefor all the abstract functions he inherited from him.



Defining abstract functions in Python

In the following example, we have defined a class with a name ParentClassthat contains 3 functions as follows:

  • Regular function namedm1.

  • Abstract and empty functionm2.

  • An abstract function with the content of its namem3.

Then we created a class named ChildClassinherit from the classParentClass.

Note: Classes ChildClassare forced to doOverrideFor every abstract function inherited from the classParentClass.

Example

ParentClass.py
# So that we can use the abc in the @abstractmethod module and the word abc here we have included the class
		  from abc import ABC, abstractmethod
	  
	  
		  # So that it becomes a simple ABC class and we make it inherit from the ParentClass class, here we create a class named
		  class ParentClass(ABC):
	  
		  # m1 Here we have defined a regular function named
		  def m1(self):
		  print('m1: Normal method defined by ParentClass')
	  
		  # m2 Here we have defined an abstract and empty function named
		  @abstractmethod
		  def m2(self):
		  pass
	  
		  # m3 Here we have defined an abstract function with a command to print its name
		  @abstractmethod
		  def m3(self):
		  print('m3: Default content is written by ParentClass')
	

ChildClass.py
# So that we can inherit from it the ParentClass which is in the ParentClass module here we have included the class
		  from ParentClass import ParentClass
	  
	  
		  # ParentClass inherits from the ChildClass class Here we have created a class named
		  class ChildClass(ParentClass):
	  
		  # ParentClass because this function was defined as an abstract function in the m2() class of the Override function here we did
		  def m2(self):
		  print('m2: Its content is written by ChildClass')
	  
		  # ParentClass because this function was defined as an abstract function in the m3() class of the Override function here we did
		  def m3(self):
		  super().m3() # Then we added the command to print ParentClass in m3() class Note that we called the function
		  print('m3: ChildClass add his own code too')
	

Test.py
# So that we can create an object from ChildClass here we have included the class
		  from ChildClass import ChildClass
	  
	  
		  # obj named ChildClass Here we created an object from the class
		  obj = ChildClass()
	  
		  # obj Here we called the three functions in the object
		  obj.m1()
		  obj.m2()
		  obj.m3()
	

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

m1: Normal method defined by ParentClass
m2: Its content is written by ChildClass
m3: Default content is written by ParentClass
m3: ChildClass add his own code too

 Examples of abstraction in Python

An example showing the usefulness of defining an abstract class in Python


In the following example, we have defined a class with an Aabstract name and placed an abstract function in itm1.
Then we defined a class with an abstract name that Binherits from the class A, and we put in it an abstract function with its namem2.
Then we defined a normal class whose name Cinherits from the class Band doesOverridefor functions m1()andm2().
Finally, we create an object from the class Cand call both functions from it.


Example of abstraction in Python

A.py
      # So that we can use the abc in the @abstractmethod module and the word abc here we have included the class
		  from abc import ABC, abstractmethod
	  
	  
		  # Until the class becomes just ABC and we make it inherit from class A here we have created a class named
		  class A(ABC):
	  
		  # m1 Here we have defined an abstract and empty function named
		  @abstractmethod
		  def m1(self):
		  pass
    

B.py
      # So that we can inherit from A so that we can define an abstract function + class @abstractmethod here include the word
		  from abc import abstractmethod
		  from A import A
	  
	  
		  # m1() until it becomes an abstract class and contains the function ABC, which in turn inherits from class A and we made it inherit from class B here we created a class named
		  class B(A):
	  
		  # m2 Here we have defined an abstract and empty function named
		  @abstractmethod
		  def m2(self):
		  pass
	  
		  # Also A from the class m1() inherit the abstract function B Don't forget that the class
    

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
	  
	  
		  # for all the abstract functions that Override inherited, so this class is forced to do B inherit from class C here we define a class named
		  class C(B):
	  
		  # m1() of the Override function here we did
		  def m1(self):
		  print('m1 content is written in the class c')
	  
		  # m2() of the Override function here we did
		  def m2(self):
		  print('m2 content is written in the class c')
    

Test.py
      # So that we can create an object from ChildClass here we have included the class
		  from C import C
	  
	  
		  # obj named C here we created an object from the class
		  obj = C()
	  
		  # obj Here we have called both functions in the object
		  obj.m1()
		  obj.m2()
    

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

m1 content is written in the class c
m2 content is written in the class c

In the following example, we built a class with just its name Personthat contains the function __init__()in which we put 4 properties of their namename, gender, brithdayAnd theis_married,In addition to an abstract and empty function namedprint_info().

Then we defined a class whose name Studentinherits from the class Personand has an additional property calledspecialization.
Then we defined a class whose name Employeeinherits from the class Personand has an additional property calledsalary.
The idea here is that any class that will be created to represent a human being must inherit from the class Personthat has characteristics common to all human beings and must doOverridefor the function print_info()to display all the property values ​​in the inherited class in order.

Finally, we created an object from the class Studentand an object from the class Employeeand called the function print_info()from each of them.


Example 2 of abstraction in Python

Person.py
      # So that we can use the abc in the @abstractmethod module and the word abc here we have included the class
		  from abc import ABC, abstractmethod
	  
	  
		  # This class is considered the basic class for any human being, as every person has basic information such as: name, gender, date of birth and marital status
		  # To become a mere ABC class, we made this class inherit from the class
		  class Person(ABC):
	  
		  # which we want to be owned by any person defined in which we set the properties of the class __init__() here we have defined the function
		  def __init__(self, name, gender, birthday, is_married):
		  self.name = name
		  self.gender = gender
		  self.birthday = birthday
		  self.is_married = is_married
	  
		  # The class that inherits it to determine how it wants people's properties to be displayed Override This function should do for them
		  @abstractmethod
		  def print_info(self):
		  pass
    

Student.py
      # So that we can inherit from it Person.py which is in the Person file here we have included the class
		  from Person import Person
	  
	  
		  # Because Person can use it as the main class for creating any student, this class is inherited from the Student class. Here we have defined a class named
		  class Student(Person):
	  
		  # which will be owned by any object we create from it Student in which we put the properties of the class __init__() here we have defined the function
		  def __init__(self, name, gender, birthday, is_married, specialization):
		  # that we enter when creating the object name and gender, birthday, is_married and we pass them the parameter values ​​of Person present in the __init__() class here we called the function
		  super().__init__(name, gender, birthday, is_married)
		  The # that we mentioned in this class will be given the last value we pass in the parentheses of the object we create from this class's specialization property
		  self.specialization = specialization
	  
		  # Student to specify how all property values ​​owned by any object we create from the print_info() class will be printed to the Override function here we did
		  def print_info(self):
		  print('name:', self.name)
		  print('gender:', self.gender)
		  print('birthday:', self.birthday)
		  print('is married:', self.is_married)
		  print('specialization:', self.specialization)
		  print('---------------------------------')
    

Employee.py
      # So that we can inherit from it Person.py which is in the Person file here we have included the class
		  from Person import Person
	  
	  
		  # Because Person can benefit from it, it is considered the main class for creating any student, this class we made it inherit from the Employee class. Here we defined its name class
		  class Employee(Person):
	  
		  # which will be owned by any object we create from it the Employee in which we put the properties of the class __init__() here we have defined the function
		  def __init__(self, name, gender, birthday, is_married, salary):
		  # that we enter when creating the object name and gender, birthday, is_married and we pass them the parameter values ​​of Person present in the __init__() class here we called the function
		  super().__init__(name, gender, birthday, is_married)
		  The # that we mentioned in this class will be given the last value we pass in the parentheses of the object we create from this class salary property
		  self.salary = salary
	  
		  # Employee to specify how all property values ​​owned by any object we create will be printed from the print_info() class of the Override function here we did
		  def print_info(self):
		  print('name:', self.name)
		  print('gender:', self.gender)
		  print('birthday:', self.birthday)
		  print('is married:', self.is_married)
		  print('salary:', self.salary)
		  print('---------------------------------')
    

Test.py
      # So that we can create two objects from Employee.py which is in the file Employee and the Student.py class which is in the Student file here we have included the class
		  from Employee import Employee
		  from Student import Student
	  
	  
		  # e named Employee and an object of the class s named Student Here we created an object of the class
		  s = Student('Mhamad', 'Male', '1994', False, 'Computer Science')
		  e = Employee('Rana', 'Female', '1986', True, 1500)
	  
		  # To display in order their values ​​of s and e that are in each of the print_info() object here we called the function
		  s.print_info()
		  e.print_info()
    

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

name: Mahamad
gender: Male
birthday: 1994
is married: False
specialization: Computer Science
-----------------------------
name: Rana
gender : Female
birthday: 1986
is married: True
salary: 1500
-----------------------------

You will see benefittheAbstractionAlso in advanced lessons when you use ready-made classes that allow you to deal with networks(Networks), interfaces(GUI)and databases(DataBases)Easily. You will also see it when you are working on building large projects, forcing you to use this method to facilitate the work on the project.