đź§© Introduction to Encapsulation in Python
Encapsulation is one of the key principles of object-oriented programming (OOP). It means restricting direct access to specific attributes or methods to prevent accidental modification.
👉 In Python, encapsulation is achieved mainly through conventions rather than strict enforcement.
🔑 Public, Protected, and Private in Python
Public Members: Accessible everywhere (default in Python).
Protected Members: Indicated with a single underscore _member
. This convention suggests that the member should not be accessed directly outside the class.
Private Members: Indicated with a double underscore __member
. Python performs name mangling to make it more challenging (but not impossible) to access these members.
đź“– Public Members Example
class Person:
def __init__(self, name):
self.name = name # public
p = Person("Alice")
print(p.name) # Accessible directly
Output:
Alice
🛡️ Protected Members Example
class Person:
def __init__(self, name):
self._name = name # protected
class Student(Person):
def display(self):
print("Student name:", self._name)
s = Student("Bob")
s.display()
print(s._name) # Technically accessible, but not recommended
Output:
Student name: Bob
Bob
👉 _name
is a protected member. It is suggested not to use it outside the class, but Python doesn’t block it.
đź”’ Private Members Example
class Person:
def __init__(self, name):
self.__name = name # private
def display(self):
print("Person name:", self.__name)
p = Person("Charlie")
p.display()
# Trying to access directly will fail
print(p.__name)
Output:
Person name: Charlie
Traceback (most recent call last):
...
AttributeError: 'Person' object has no attribute '__name'
👉 Here, __name
is private. Python internally renames it to _Person__name
(name mangling).
🔍 Accessing Private Members with Name Mangling
Even though private members can’t be accessed directly, you can still access them using the mangled name:
print(p._Person__name)
Output:
Charlie
👉 This shows that Python’s private is not truly private—it’s just harder to access.
🏗️ Key Differences
Type | Syntax | Accessibility |
---|
Public | member | Fully accessible everywhere |
Protected | _member | Accessible, but discouraged outside class |
Private | __member | Name-mangled, harder to access outside class |
📌 Summary
Python doesn’t enforce strict access modifiers like other languages. Instead, it relies on naming conventions to indicate the intent of access control. Public members are open to all, protected members (with _
) are meant for internal use within classes and subclasses, and private members (with __
) use name mangling to discourage external access. This flexibility gives developers freedom but also places responsibility on them to respect these conventions. 🚀