Sobes.tech
Junior — Middle

How is the principle of encapsulation implemented in Python?

sobes.tech AI

Answer from AI

In Python, encapsulation is implemented through naming conventions and special mechanisms, as the language does not have strict privacy like some other languages.

  • Public attributes and methods — names without underscores, accessible everywhere.
  • Protected attributes — names with a single underscore _attribute, indicating that the element is intended for internal use, but technically accessible from outside.
  • Private attributes — names with double underscores __attribute, which trigger name mangling, making it harder to access from outside the class.

Example:

class MyClass:
    def __init__(self):
        self.public = "accessible to all"
        self._protected = "recommended not to use outside the class"
        self.__private = "hidden from external access"

obj = MyClass()
print(obj.public)        # works
print(obj._protected)    # works, but not recommended
# print(obj.__private)   # will cause an error
print(obj._MyClass__private)  # access via name mangling

Thus, encapsulation in Python is more about convention and using mangling mechanisms rather than strict restrictions.

How is the principle of encapsulation implemented in… - sobes.tech