Sobes.tech
Junior — Middle

How is data hiding achieved in Python within classes, and how is access to it restricted?

sobes.tech AI

Answer from AI

In Python, data hiding within classes is achieved through conventions and attribute naming mechanisms, rather than strict access restrictions like in some other languages.

  • A single underscore _variable indicates that an attribute or method is protected and not intended for use outside the class or its subclasses. This is a convention, not a prohibition.
  • Double underscores __variable trigger name mangling, where the attribute's name is changed within the class to make external access more difficult. For example, __var inside class MyClass becomes _MyClass__var.

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 (possible, but not recommended)
# print(obj.__private)  # AttributeError
print(obj._MyClass__private)  # 3 (access via name mangling)

Thus, in Python, data hiding is more of an agreement and uses name mangling to complicate direct access.

How is data hiding achieved in Python within classes… - sobes.tech