Sobes.tech
Junior — Middle

What are the differences between access modifiers public, protected, and private in programming languages?

sobes.tech AI

Answer from AI

In Python, there are no strict access modifiers like in some other languages (e.g., Java or C++), but there are conventions:

  • public — attributes and methods accessible everywhere. Just regular names.
  • protected — denoted by a single underscore _name. This convention indicates that the attribute or method is intended for internal use within the class and its subclasses, but is technically accessible from outside.
  • private — denoted by double underscores __name. This triggers name mangling, which makes it more difficult to access the attribute from outside the class, but does not make it completely inaccessible.

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’s not recommended to do so)
# print(obj.__private)  # Error
print(obj._MyClass__private)  # 3, access via name mangling