Encapsulation and Polymorphism in Python

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

1. Encapsulation in Python

Encapsulation is one of the essential features of object-oriented programming. The goal is to guarantee that the class contains all the necessary properties and methods. Encapsulation will prevent direct access and modification of the properties and methods of a class. From there, it helps to hide data.

Python displays encapsulation by declaring the attributes and methods in private mode. Private attributes and methods are only accessible and usable within the class in which they are defined. Python uses underscore _ or double underscore __ as a prefix to indicate that an attribute or method is private.

class Person:
  def __init__(self):
    self.__age = 20

  def showAge(self):
      print(self.__age)

  def setAge(self, age):
      self.__age = age

david = Person()
print("Age of david: ", end='')
david.showAge()
david.__age = 99
print("Age of david after david.__age = 99: ", end='')
david.showAge()
david.setAge(99)
print("Age of david after david.setAge(99): ", end='')
david.showAge()

Result

Age of david: 20
Age of david after david.__age = 99: 20
Age of david after david.setAge(99): 99

In the example above, we define a class Person. The class Person has a private attribute __age. When we change this variable outside of the Person class david.__age = 99, it will not be changed inside the object david of the class Person. The value of the __age variable of the david object will be changed with the setAge() function.

Private properties and methods are only accessible within the class where they are defined.

class Person:
  def __init__(self):
    self.__age = 20

  def showAge(self):
      print(self.__age)

  def setAge(self, age):
      self.__age = age
  # private method
  def __info():
    print("Info of a person.")

david = Person()
# AttributeError: 'Person' object has no attribute '__age'
print(david.__age)
# AttributeError: 'Person' object has no attribute '__info'
david.__info()

2. Polymorphism in Python

Polymorphism means that similar objects and methods can have different behaviors depending on the situation.

class Vietnam():
  def capital(self):
    print("capital: Ha Noi")

  def language(self):
    print("language: Vietnamese")

class Japan():
  def capital(self):
    print("capital: Tokyo")

  def language(self):
    print("language: Japanese")

# common method
def aboutCountry(country):
  country.capital()
  country.language()

# create objects
vn = Vietnam()
jp = Japan()

# passing the object
print("about Vietnam")
aboutCountry(vn)
print("about Japan")
aboutCountry(jp)

Result

about Vietnam
capital: Ha Noi
language: Vietnamese
about Japan
capital: Tokyo
language: Japanese

In the example above, the classes Vietnam and Japan both have capital() and language() functions. But they will produce different results when called through the aboutCountry() function.

You are overriding a method when inheriting is also an example of polymorphism.

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

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

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

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

# create objects
kane = Person("Kane", 29)
kane.info()
kane = Teacher("Kane", 29, "5000000")
kane.info()

Result

Kane, 29 years old.
Kane, 29 years old, salary: 5000000

In the example above, the class Teacher inherits the class Person. The Teacher class overrides the info() function inherited from Person. Then, we create objects of Person and Teacher. These objects all call a function named info() but they return different results depending on the type of object.

5/5 - (1 vote)
Previous and next lesson in subject<< Multiple Inheritance in PythonOperators overloading in Python >>

Leave a Reply

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