Encapsulation in Python

In python, encapsulation is a process of binding the data members such as variables, properties, etc., and member functions into a single unit. The perfect example for encapsulation is class because it will wrap all the variables, functions, etc., into a single entity.


In python, encapsulation is helpful to prevent the accidental modification of data. For example, the class that you will create with required variables and functions will not allow you to modify the class members directly. Instead, you need to create an object to access or change those class members.

Python Encapsulation Example

Following is the example of implementing the encapsulation in python.


class user:
   id = 10
   name = "Suresh"

   def __init__(self, uid, uname):
     self.id = uid
     self.name = uname

   def userdetails(self):
     print("Id: {}, Name: {}".format(self.id, self.name))

u1 = user(2, "Rohini")
u1.id = 30
u1.name = "Trishi"

If you observe the above example, we created a class (user) with required variables and functions. To access the class members, we created an object (u1) and performing the required operations.


The above python encapsulation example will return the result as shown below.


Id: 30, Name: Trishi

If required, you can also implement the access level restrictions on encapsulated class members using access modifiers in python based on your requirements.