How Encapsulation is Achieved in Python?

How Encapsulation is Achieved in Python?

A Comprehensive Guide with example code

Scope of the Article

  • In this article, we will learn about encapsulation in python.
  • Next, we will discuss the need for encapsulation in python and different types of access modifiers in python.
  • Then, we will know how encapsulation is achieved in python.

Encapsulation

Encapsulation is a concept under object-oriented programming (OOP), object-oriented programming concepts also include data abstraction, inheritance, and polymorphism.

The encapsulation concept describes the data bundling and wrapping of data and methods within a single class or a single method.

While accessing the methods and variables has some restrictions which can prevent the modification of data.

If we take an example to describe encapsulation in python, class is a good example of encapsulation in which all the data are methods and functions that are encapsulated easily.

Example Code1:

class student:
    def __init__(self, name, roll, marks):
        self.name = name
        self.roll = roll
        self.marks = marks
    def display(self):
        print(“Student Name: ”, self.name)
        print(“Roll Number: ”, self.roll)
    def performance(self):
        print(“Student Named ”, self.name,“had obtained marks of : ”, self.marks)
s = student(‘Rama’, “180”, “98”)
s.display()
s.performance()

Output:

Student Name: Rama
Roll Number: 180
Student Named Rama had obtained marks of 98

In this example, we created a class named student and defined 2 attributes such as name, roll, and marks as variables and implemented methods named display() and performance().

Similarly, we can take another example that describes the employee and his salary.

Example Code2:

class emp:
    def __init__(self, name, id, salary):
        self.name = name
        self.id = id
        self.salary = salary
    def display(self):
        print(“Employee Name: ”, self.name)
        print(“Employee id: ”, self.id)
    def performance(self):
        print(“Employee Named ”, self.name,“had Salary of : ”, self.salary, “lpa”)
s = student(‘Rama’, “180”, “9.8”)
s.display()
s.performance()

Output:

Employee Name: Rama
Employee id: 180
Employee Named Rama had Salary of 9.8 lpa

In this example, we created a class named Employee, defined 2 attributes such as name, id, and salary as variables, and implemented methods named display() and performance().

How Encapsulation is achieved in python?

  • Encapsulation in python, provides well-defined, readability and security.
  • Encapsulation prevents accidental mistakes or modifications done by mistakes.
  • Encapsulation in python can be achieved by access modifiers, by declaring members of the class by either protected or private access modifiers.

Access Modifiers in python

Encapsulation in python using Private Access Modifiers:

Private access modifier, if a variable or method have declared as private then it cannot be accessed outside the class.

Basically, python has no private access modifier for variables, variables can be accessed outside the class.

To use a private access modifier in python, we define it with ‘__’ (double underscore) as the prefix of the member’s names.

Let us understand this with an example, how we can implement encapsulation using private access modifiers,

Example Code1

class pcla1:
    def __init__(self):
        self.name = “Rama”
        self.__id = 123
class pcla2(pcla1):
    def __init__(self):

    pcla1.__init__(self)
    print(“Calling the private member of pcla1 in pcla2”)
    print(self.__id)

c = pcla1()
print(c.name)

Output:

Rama

In this example, we created a class named pcla1 and another class pcla2, declared variable id as private in class pcla1, and tried to use it in pcla2, but the code doesn’t execute.

Example Code2

class area:
    __len = 0
    __bre = 0
    def __init__(self):
        self.__len = 5
        self.__bre = 10

print(self.__len)
print(self.__bre)
print(self.__len * self.bre)
a = area()
print(a.len)
print(a.bre)

Output:

5
10
50
Traceback (most recent call last):
  File "main.py", line 12, in <module>
    print(a.len)
AttributeError: ‘area’ object has no attribute 'len'

In this example, we created a class named area, declared variables len and bre as private variables in the class area, and tried to change them. Still, an error occurred because the variables declared in private cannot be modified permanently.

Screenshot 2022-10-31 at 6.30.53 PM.png

Encapsulation in python using Protected Access Modifiers:

The protected access modifier can be accessed only within the class but cannot be accessed by any other class which is outside the class.

To use a protected access modifier in python, we define it with ‘_’ (single underscore) as the prefix of the members’ names.

Let us understand this with an example, how we can implement encapsulation using protected access modifiers,

Example Code1

class prcla1:
    def __init__(self):
        self._name = “Rama”
        self._id = 123
class prcla2(prcla1):
    def __init__(self):

    pcla1.__init__(self)
    print(“Calling the protected member of prcla1 in prcla2”)
    print(self._id)

    self._id = 535
    print(“Modifying  the protected member of prcla1 in prcla2”)
    print(self._id)

c1 = prcla1()
c2 = prcla2()

print(“Value of id, access the protected member of object c1”, c1.id)
print(“Value of id, access the protected member of object c2”, c2.id)

Output:

Calling the protected member of prcla1 in prcla2 123
Modifying  the protected member of prcla1 in prcla2 535
Value of id, access the protected member of object c1 535
Value of id, access the protected member of object c2 123

In this example, we created a class named prcla1 and another class prcla2, declared variables name and id as protected in class prcla1 and tried to use it in prcla2, and tried to modify it in the prcla2 class. Modified but did not reflect the prcla1 class.

Here we can say that we can manage the things, which can happen accidentally such as accidental modifications.

Example Code2

class stu:
    _name = “Rama”
    _id = 20
    _marks = 98
class stu1(stu):
    def __init__(self):
        print(“Student Name: ”, self._name)
        print(“Student Id: ”, self._id)
        print(“Student Marks: ”, self._marks)
S = stu1()
print(“Student Name: ”, s.name)
print(“Student Id: ”, s.id)
print(“Student Marks: ”, s.marks)

Output:

Student Name: Rama
Student Id: 20
Student marks: 98
<Error message>
Traceback (most recent call last):
  File "main.py", line 11, in <module>
    print(“Student Name: ”, s.name)
AttributeError: ‘stu1’ object has no attribute 'name'

Now, we can say that encapsulation is achieved by private and protected access modifiers in python.

Encapsulation has some advantages and benefits like giving security by hiding irrelevant data that we can call data hiding and simplicity which maintains the application by keeping classes separated to have a much clearer view.

Conclusion

  1. Encapsulation in python is one of the concepts in object-oriented programming concepts, other concepts include data abstraction, inheritance, and polymorphism.
  2. Encapsulation in python can be achieved by the access modifiers such as private and protected in python.
  3. Private access modifier, if a variable or method have declared as private then it cannot be accessed by outside the class.
  4. Protected access modifier, can be accessed only within the class but cannot be accessed by any other class which is outside the class.
  5. Encapsulation in python can be achieved using private by using 2 underscores as prefixes of the declaration of a variable or method.
  6. Encapsulation in python can be achieved by using 1 underscore as the prefix of the declaration of a variable or method.
  7. Encapsulation has great needs and advantages in python.
  8. These are the main things that we discussed in this article, go through each and every point covered in the article you will get a clear idea.