Sobes.tech
Junior — Middle

How is internal implementation of an object hidden and data protected from external access in Python?

sobes.tech AI

Answer from AI

In Python, the concealment of an object's internal implementation and data is achieved through conventions and encapsulation mechanisms:

  • Single underscore (_var) — indicates that an attribute or method is intended for internal use (protected), but is technically accessible from outside.
  • Double underscore (__var) — results in name mangling (changing the name), which makes external access more difficult, for example, __var becomes _ClassName__var. This serves to prevent accidental overriding and hide data.

Example:

class MyClass:
    def __init__(self):
        self.public = "accessible to everyone"
        self._protected = "for internal use"
        self.__private = "hidden from external access"

obj = MyClass()
print(obj.public)          # accessible
print(obj._protected)      # accessible, but not recommended
print(obj._MyClass__private)  # access to "private" attribute via name mangling

Thus, Python does not have strict private access, but there are conventions and mechanisms that allow hiding data from direct external access.