Python  

How to access private and protected members in Python?

๐Ÿงฉ 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

  1. Public Members: Accessible everywhere (default in Python).

  2. Protected Members: Indicated with a single underscore _member. This convention suggests that the member should not be accessed directly outside the class.

  3. 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

TypeSyntaxAccessibility
PublicmemberFully accessible everywhere
Protected_memberAccessible, but discouraged outside class
Private__memberName-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. ๐Ÿš€