Python Encapsulation

🐍 Python Encapsulation

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

ModifierHow it worksExample
PublicCan be accessed anywhereself.name
Protected (single underscore _)Should not be accessed outside class (convention)self._salary
Private (double underscore __)Cannot be accessed directly outside classself.__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:

print(b._BankAccount__balance) # 5000

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:


 

@property makes your code cleaner and Pythonic.


 7️⃣ Summary Table

FeatureDescription
PublicAccessible everywhere (self.name)
ProtectedSingle underscore _var (convention)
PrivateDouble underscore __var (restricted access)
GetterMethod to get private attribute
SetterMethod to safely set private attribute
@propertyPythonic 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

You may also like...