Sobes.tech
Middle+

How is encapsulation implemented in Python? Tell about access modifiers.

sobes.tech AI

Answer from AI

In Python, encapsulation is implemented through naming conventions and class properties, as there are no strict access modifiers like in other languages (private, protected, public).

  • Public attributes and methods — names without underscores, accessible everywhere.
  • Protected — names with a single leading underscore _var. This is a convention indicating that the attribute or method is intended for internal use, but it is technically accessible from outside.
  • Private — names with double leading underscores __var. Python applies name mangling, changing the attribute's name inside the class to make external access more difficult.

Example:

class MyClass:
    def __init__(self):
        self.public = "accessible to all"
        self._protected = "recommended not to use outside the class and subclasses"
        self.__private = "hidden from direct 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 the name mangling mechanism rather than strict access modifiers.

How is encapsulation implemented in Python? Tell… - sobes.tech