Sobes.tech
Junior — Middle

Can you explain the principle of encapsulation in Python and how it is implemented?

sobes.tech AI

Answer from AI

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

  • Attributes and methods starting with a single underscore (_attribute) are considered "protected" — this is a convention indicating they are not intended for use outside the class or its subclasses.
  • Attributes and methods with double underscores at the beginning (__attribute) invoke the "name mangling" mechanism — the attribute's name is changed 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 use)
print(obj._MyClass__private)  # 3 (access to "private" attribute via name mangling)

Thus, encapsulation in Python is based on conventions and mechanisms, not on strict restrictions like in some other languages.