Sobes.tech
Middle

What mechanisms of encapsulation are implemented in Python?

sobes.tech AI

Answer from AI

In Python, encapsulation is implemented through conventions and mechanisms that restrict access to class attributes and methods:

  • Public attributes and methods — accessible everywhere.
  • Protected attributes — start with a single underscore _attribute. This is just a convention indicating that such attributes are not intended for external use.
  • Private attributes — start with double underscores __attribute. Python applies name mangling, changing the attribute's name inside the class to make external access more difficult.

Example:

class MyClass:
    def __init__(self):
        self.public = 1
        self._protected = 2
        self.__private = 3

obj = MyClass()
print(obj.public)       # 1
print(obj._protected)   # 2 (but it is not recommended to do so)
# print(obj.__private)  # AttributeError
print(obj._MyClass__private)  # 3, access via name mangling

Thus, encapsulation in Python is more based on conventions and language mechanisms rather than strict access restrictions, as in some other languages.