Min menu

Pages

The concept of polymorphism in Python

The concept of polymorphism in Python

Polymorphism or polymorphism(Polymorphism)It is just a method of writing code that is intended to build a function that executes different commands depending on the object that we pass to it when it is called.
Usually polymorphism is mainly related to inheritance, where the function is based on the parent class, but when we call it we pass an object from one of the classes that it inherits from.

So, polymorphism can be achieved in different ways depending on the code you are building or using.
And sometimes you find yourself using the same function with an array or with a text, so you find that the way this function works and what it returns to you is completely different depending on the type of object you pass to it.

The concept of polymorphism in Python Polymorphism is just a method of writing code that is intended to construct a function that performs different commands depending on the object that we pass to it when it is called. Usually polymorphism is mainly related to heredity where the function is based on the parent class, but when we call it we pass it on to an object from one of the classes it inherits from. So, polymorphism can be achieved in different forms depending on the code that you build or use. Sometimes you find yourself using the same function with an array or with text, and you find that the way this function works and what it returns to you differs completely depending on the type of object that you pass to it.

Ready functions in Python that apply the principle of polymorphism

One of the most prominent functions that we use that apply the principle of polymorphism is the function len()that we have previously dealt with in more than one lesson, but each time we used it for a different reason.
For example, when a text is passed to this function, it returns the number of its characters. And when you pass an array to this function, it returns the number of its elements.


In the following example, we have defined an object whose name we stringput in it a plain text, and for an object of its type we put 5 elements in it. Then we print what the function will return if the object and the object are passed to it.listaList
len()stringaList

Example

Test.py
# Contains string text Here we have defined an object named
		  string = 'Python tutorial for beginners'
	  
		  # We put in it an array of integers called aList, here we have defined
		  aList = [10, 20, 30, 40, 50]
	  
		  # len() that the string function will return here we have shown the number of characters of the object
		  print('Number of characters in string is:', len(string))
	  
		  # len() that the aList function will return here we have shown the number of elements of the object
		  print('Number of elements in aList is:', len(aList))
	

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

Number of characters in string is: 29
Number of elements in aList is: 5

So, we notice that when the object is passed to the stringfunction len()it returns the number of its characters. And when the object is passed aListit returns the number of its elements. Which means that the function len()checks on the type of the object being passed to it and on the basis of its type it returns the value.



Technical information

In Python, there is a ready-made function whose name isinstance()can be used to check whether an object is created from a particular class or not.
If it was originated from it, it will returnTrue,If it was not originated from it, it returnsFalse.


Now, since the function len()is checking for the type of object we're passing to it, that means it's probably defined like this.

def len(obj):
	
		# str is obj here like we said: Is the type of object passed where the object is
		if isinstance(obj, str):
		# any text, the code to count its chars will be executed and then return str if the object type passed to the function is
	
		# list is obj here like we said: Is the type of object passed where the object is
		elif isinstance(obj, list):
		# any array, the code to count the number of its elements will be executed and then return list if the type of object passed to the function is
  

Building a function that applies polymorphism in Python

In the following example, we have defined a function whose name print_sum()is designed to handle three types of objects.

  • If you pass it an integer, which type is itint,It prints the result of adding the numbers in it.

  • If you pass it a text that represents an integer, which type is itstr,It converts the letters in it to numbers and then prints the result of adding these numbers.

  • If you pass it an array of type listcontaining integers or strings representing integers, it prints the sum of these elements.

Example

Test.py
# obj contains a parameter named print_sum. Here we have defined a function named
		  def print_sum(obj):
	  
		  # We will use it when performing any addition, so we have prepared it and given it the value 0 s variable
		  s = 0
	  
		  # i.e. if its value is an integer, int if its value is obj The following code is tasked with calculating the sum of the numbers in the object
		  if isinstance(obj, int):
		  while obj:
		  s += obj %10
		  obj //= 10
		  print('Sum of digits:', s)
	  
		  # that is, if its value is a text representing an integer, str if its value is obj The following code is to calculate the result of adding the numbers in the object
		  elif isinstance(obj, str):
		  for c in obj:
		  s += int(c)
		  print('Sum of characters:', s)
	  
		  # i.e. if its value is an array, list if it is obj The following code is tasked with calculating the result of summing the values ​​of the elements in the object
		  elif isinstance(obj, list):
		  for e in obj:
		  s += int(e)
		  print('Sum of elements:', s)
	  
		  # list or str or int is not obj The following code is interested in printing an alert clause in case it is an object's value type
		  else:
		  print('This function is not made for this type!')
	  
	  
		  print_sum(12345) # and pass its integer print_sum() here we called the function
		  print_sum('12345') # and passing a text representing an integer to it print_sum() here we called the function
		  print_sum([1, 2, 3, 4, 5]) # have a list and pass an array of numbers as print_sum() here we called the function
		  print_sum((1, 2, 3, 4, 5)) # have a tuple and pass an array of numbers as print_sum() here we called the function
	

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

Sum of digits: 15
Sum of characters: 15
Sum of elements: 15
This function is not made for this type!

Applying Polymorphism with Inheritance in Python

In the following example, we defined a class whose name BaseCountryis just the basic class for any class that represents a country, and therefore any class we will create to represent a country must inherit from it. In this class we have also prepared 3 abstract functions.
Then we defined a class whose name is a class, and a class Egyptwhose name Australiainherits from the class BaseCountryand they doOverrideFor all functions that they inherited from him.
Then we created a function named print_country_info()its task to call all the functions in the object that we pass to it provided that this object was created from a class that inherits from the classBaseCountry.

Finally, we created an object from the class Egyptand an object from the class Australiaand passed each of them to the functionprint_country_info().

Example

BaseCountry.py
# Contains 3 empty functions BaseCountry Here we have created a class named
		  class BaseCountry:
	  
		  def name(self):
		  pass
	  
		  def capital(self):
		  pass
	  
		  def language(self):
		  pass
	

Egypt.py
# So that we can inherit from BaseCountry which is in the BaseCountry module, here we have included the class
		  from BaseCountry import BaseCountry
	  
	  
		  # For the three functions in it Override and do BaseCountry inherit from the class Egypt Here we created an empty class named
		  class Egypt(BaseCountry):
	  
		  def name(self):
		  print('Country: Egypt')
	  
		  def capital(self):
		  print('Capital: Cairo')
	  
		  def language(self):
		  print('Language: Arabic')
	

Australia.py
# So that we can inherit from BaseCountry which is in the BaseCountry module, here we have included the class
		  from BaseCountry import BaseCountry
	  
	  
		  # For the three functions in it Override and doing BaseCountry inherit from the Australia class Here we have created an empty class named
		  class Australia(BaseCountry):
	  
		  def name(self):
		  print('Country: Australia')
	  
		  def capital(self):
		  print('Capital: Canberra')
	  
		  def language(self):
		  print('Language: English')
	

Test.py
# So that we can deal with them in Australia, Egypt, BaseCountry, here we have included the classes
		  from BaseCountry import BaseCountry
		  from Egypt import Egypt
		  from Australia import Australia
	  
	  
		  # obj When this function is called, if the object that is passed is in the place of the parameter .obj has one parameter named print_country_info here we have defined a function named
		  # else The three functions in it will be called. If not, the print command placed in the BaseCountry statement will be executed as an object of a class that inherits from the class
		  def print_country_info(obj):
		  if isinstance(obj, BaseCountry):
		  obj.name()
		  obj.capital()
		  obj.language()
		  else:
		  print('You should pass an object of type BaseCountry')
		  print('------------------------------------------------' )
	  
	  
		  # australia is called Australia, and an object from the class egypt is called Egypt. Here we have created an object from the class
		  egypt = Egypt()
		  australia = australia()
	  
		  # In order to call the three functions, including australia and egypt, we passed the two objects print_country_info() here we called the function
		  print_country_info(egypt)
		  print_country_info(australia)
	  
		  # else and pass a plain text to it. Notice how it will execute the print command given in the print_country_info() statement. Here we have called the function
		  print_country_info('A string object')
	

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

Country: Egypt
Capital: Cairo
Language: Arabic
------------------------------------------- -----
Country: Australia
Capital: Canberra
Language: English
------------------------------------ ----------
You should pass an object of type BaseCountry
-------------------------------- --------

Applying the principle of polymorphism with arrays and inheritance in Python

In the following example, we defined a class whose name BaseCountryis just the basic class for any class that represents a country, and therefore any class we will create to represent a country must inherit from it. In this class we have also prepared 3 abstract functions.
Then we defined a class whose name is a class, and a class Egyptwhose name Australiainherits from the class BaseCountryand they doOverrideFor all functions that they inherited from him.

In the end, we created an object from the class Egyptand an object from the class Australia, and then we put them in listits namecountries.
And then we create a loop that passes all the objects placed in the object and calls the three functions from each object created from a class that inherits from the classBaseCountry.

Example

BaseCountry.py
# Contains 3 empty functions BaseCountry Here we have created a class named
		  class BaseCountry:
	  
		  def name(self):
		  pass
	  
		  def capital(self):
		  pass
	  
		  def language(self):
		  pass
	

Egypt.py
# So that we can inherit from BaseCountry which is in the BaseCountry module, here we have included the class
		  from BaseCountry import BaseCountry
	  
	  
		  # For the three functions in it Override and do BaseCountry inherit from the class Egypt Here we created an empty class named
		  class Egypt(BaseCountry):
	  
		  def name(self):
		  print('Country: Egypt')
	  
		  def capital(self):
		  print('Capital: Cairo')
	  
		  def language(self):
		  print('Language: Arabic')
	

Australia.py
# So that we can inherit from BaseCountry which is in the BaseCountry module, here we have included the class
		  from BaseCountry import BaseCountry
	  
	  
		  # For the three functions in it Override and doing BaseCountry inherit from the Australia class Here we have created an empty class named
		  class Australia(BaseCountry):
	  
		  def name(self):
		  print('Country: Australia')
	  
		  def capital(self):
		  print('Capital: Canberra')
	  
		  def language(self):
		  print('Language: English')
	

Test.py
# So that we can deal with them in Australia, Egypt, BaseCountry, here we have included the classes
		  from BaseCountry import BaseCountry
		  from Egypt import Egypt
		  from Australia import Australia
	  
	  
		  # australia is called Australia, and an object from the class egypt is called Egypt. Here we have created an object from the class
		  egypt = Egypt()
		  australia = australia()
	  
		  # countries we named it list in australia and egypt here we put the two objects
		  countries = [egypt, australia]
	  
		  # country and each time you store a single object in the countries object here we have created a loop that passes over every object (any object) in the object
		  # The three functions in it BaseCountry will be called, whose parent is an object of class that inherits from class country if it is
		  for country in countries:
		  if isinstance(country, BaseCountry):
		  country.name()
		  country.capital()
		  country.language()
		  print('-----------------')
	

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

Country: Egypt
Capital: Cairo
Language: Arabic
------------------
Country: Australia
Capital: Canberra
Language: English
------------------ ----