Python Encapsulation
🐍 Python Encapsulation — Complete Guide
Encapsulation is an OOP principle that restricts direct access to some attributes and methods of a class.
It protects data and allows controlled access through getter and setter methods.
🔹 1️⃣ What is Encapsulation?
-
Bundling data (attributes) and methods inside a class.
-
Hiding sensitive data using private variables.
-
Providing controlled access to attributes.
🔹 2️⃣ Access Modifiers in Python
| Modifier | How it works | Example |
|---|---|---|
| Public | Can be accessed anywhere | self.name |
Protected (single underscore _) |
Should not be accessed outside class (convention) | self._salary |
Private (double underscore __) |
Cannot be accessed directly outside class | self.__balance |
🔹 3️⃣ Example: Private Variables
Private variables cannot be accessed directly from outside the class.
🔹 4️⃣ Accessing Private Variables (Name Mangling)
Python internally changes __balance to _ClassName__balance:
Direct access is possible but not recommended.
🔹 5️⃣ Getter and Setter Methods
Use methods to access or modify private variables safely.
🔹 6️⃣ Using @property Decorator
Python allows getter/setter using decorators:
@propertymakes your code cleaner and Pythonic.
🔹 7️⃣ Summary Table
| Feature | Description |
|---|---|
| Public | Accessible everywhere (self.name) |
| Protected | Single underscore _var (convention) |
| Private | Double underscore __var (restricted access) |
| Getter | Method to get private attribute |
| Setter | Method to safely set private attribute |
@property |
Pythonic way to create getter/setter |
🔹 8️⃣ Benefits of Encapsulation
-
Data protection from accidental modification
-
Clean and maintainable code
-
Ability to add validation logic in setter methods
-
Hides internal implementation details
