Sobes.tech
Junior — Middle

Is it possible to implement data encapsulation in Python and how is it achieved?

sobes.tech AI

Answer from AI

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

  • Attributes and methods with a single underscore (_attr) are considered protected — it is a convention that they are not intended for external use.
  • Attributes with double underscores (__attr) invoke name mangling, which makes access from outside more difficult and serves to create private variables.

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)  # Error
print(obj._MyClass__private)  # 3, access via name mangling

Although Python does not have strict privacy, these mechanisms help organize encapsulation and protect data from accidental access.

Is it possible to implement data encapsulation in… - sobes.tech