Encapsulation
Understand how to use encapsulation in Python to bundle data and methods into a single unit (class) and restrict direct access to some of the object's components.
Concept
Bundle data (attributes) and methods (behaviours) into a single unit (class). It restricts direct access to some of the object's components, which can prevent the accidental modification of data. Mainly hiding internal state and implementation details.
Type of Encapsulation | Description |
---|---|
Public | Accessible from anywhere, no restrictions. |
Protected | Accessible within the class and its subclasses, but not from outside. |
Private | Accessible only within the class, not from outside or subclasses. |
Data Protection
- Prevent direct access to sensitive data.
- Validate data before modification.
- Maintains data integrity.
- Controls how data is accessed and modified.
Code Maintainability
- Internal implementation can change without affecting external code.
- External interface remains stable.
- Reduces dependencies on internal details (Reduces coupling between classes).
- Makes code easier to maintain and refactor.
Implementation
Encapsulation can be implemented through private, public, and protected attributes and methods.
Get and Set Methods
Property Decorators
You can use property decorators to create getter and setter methods for encapsulated attributes.