Junior — Middle
How is the principle of data encapsulation achieved in Python?
sobes.tech AI
Answer from AI
In Python, encapsulation is achieved through naming conventions and special mechanisms:
- Single underscore (_var) — indicates that the field or method is protected, meaning it is not intended for use outside the class or its subclasses.
- Double underscores (__var) — invoke name mangling, which makes external access more difficult, simulating privacy.
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.__private) # AttributeError error
print(obj._MyClass__private) # 3 (access via mangling)
Thus, encapsulation in Python is based on conventions and mangling mechanisms, not on strict restrictions like in some other languages.