Python Encapsulation
Encapsulation is an object-oriented programming concept that focuses on hiding internal data and allowing access only through controlled methods.
[Image visualizing the concept of OOP Encapsulation: a capsule or safe protecting internal data (variables) while exposing controlled methods (getters/setters) to the outside]In Python, encapsulation:
- Keeps data (variables) and behavior (methods) together inside a class
- Restricts direct access to sensitive data
- Protects objects from accidental misuse
This improves data safety, control, and maintainability.
Private Properties
Python allows you to make class properties private by using a double
underscore (__) before the variable name.
Example
Create a private property inside a class:
Note: Private properties cannot be accessed directly from outside the class.
Accessing Private Data (Getter Method)
To read a private value safely, you should create a getter method.
Example
Using a getter to access a private property:
Modifying Private Data (Setter Method)
To update private data, use a setter method. Setter methods can also validate values before saving them.
Example
Using a setter with validation:
Why Encapsulation Is Important
Encapsulation offers several advantages:
- Data Protection: Prevents unauthorized access
- Validation: Ensures correct data values
- Flexibility: Internal code can change without affecting users
- Control: You decide how data is read or modified
Practical Encapsulation Example
Example
Encapsulating and validating marks in a class:
Protected Properties
Python uses a single underscore (_) as a convention for protected members.
Protected properties:
- Are meant for internal use
- Can still be accessed, but should not be used directly outside the class hierarchy
Example
Using a protected property:
Note: Protected members are not strictly enforced by Python—this is a naming convention to signal intent to other developers.
Private Methods
Just like properties, methods can also be made private using double
underscores (__). Private methods can only be called from inside the class itself.
Example
Creating a private method:
Name Mangling in Python
Python internally modifies private names using a process called name mangling.
-
__valueinternally becomes_ClassName__value - This avoids accidental access and naming conflicts in subclasses
Example
Understanding name mangling:
