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.
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())
Important: Most 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.