Encapsulation in Python
Encapsulation in Python
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). Encapsulation in Python is the process of wrapping up variables and methods into a single entity. In programming, a class is an example that wraps all the variables and methods defined inside a single unit.
In the real world, consider your college as an example. Each and every department’s student records are restricted only within the respective department. CSE department faculty cannot access the ECE department student record and so on. Here, the department acts as the class and student records act like variables and methods.
Why Do We Need Encapsulation?
Encapsulation acts as a protective layer by ensuring that, access to wrapped data is not possible by any code defined outside the class in which the wrapped data are defined.
Encapsulation provides security by hiding the data from the outside world.
In Python, Encapsulation can be achieved by declaring the data members of a class either as private or protected.
In Python, ‘Private’ and ‘Protected’ are called Access Modifiers, as they modify the access of variables or methods defined in a class.
Protected Members:
- Protected members (in C++ and JAVA) are those members of the class that cannot be accessed outside the class but can be accessed from within the class and its subclasses. To do this in Python, just follow the convention by prefixing the name of the member by an underscore “_”.
Code #1
Private Member:
- The class members declared private should neither be accessed outside the class nor by any base class.
- In Python, there is no existence of Private instance variables that cannot be accessed except inside a class.
- However, to define a private member prefix the member name with double underscore “__”.
Login/Signup to comment