Encapsulation in Python with Example and Detailed Explanation

Encapsulation in Python: Encapsulation in python is very small concept. By encapsulation we mean the gathering of code or data and methods operating on that data or code inside a single component and to stop the access of some of our class components.

In easy way, encapsulation is just the way to place your code at single place in such a way that it should be compact and restricted from the outside world to access protected or restricted data.

encapsulation in python

Above given image is the image of capsule. Like in capsule all the medicine content is collected and packed inside a small area. Just same like that capsule, encapsulation implements. Encapsulation in python collects its code in single area. Programs written using classes concept is the best example to achieve encapsulation in python.

Example

#example of encapsulation 

class Mobile:
    def __init__(self, brand, model, price):
        self.brand = brand
        self.model = model
        self.price = price
        
    def call(self, number):
        print("calling to "+str(number))
        
    def main(self):
        return self.brand+" "+str(self.price)
        
obj = Mobile("Cell",1100,2500)
obj.call(9888111799)
print(obj.main())
calling to 9888111799
Cell 2500

Detailed Explanation:

  • Here we have defined, class Mobile with class variables brand, model and price.
  • Also we have defined class methods i.e. call() and main()
  • If we see our program, then we will observe that our whole code is combined and well structured. This is the advantage of using object oriented approach.
  • There are two types of programming approach Procedural Programming and Object Oriented Programming.
  • It is recommended to use Object Oriented approach when we are working on large application.
  • Now comes to our program, Next we have created “obj” object reference of class Mobile and accessed our class variables and class methods respectively.

 

ImportantMost of the students and even some professionals always remain confused between encapsulation and abstraction. Actually both terms are different in meaning but they indirectly related to each other. 

  • Encapsulation: Encapsulation in python is the concept of storing the data specific to each operation at one place.
  • Abstraction: Abstraction in python is the concept of presenting only non sensitive information to user by hiding the sensitive information.
  • Optional: For achieving abstraction, we first categorize the data, let say sensitive and non-sensitive. Then we store the each category of data in different methods of class. So that later it can be used efficiently.