Junior — Middle
What is the difference between methods declared as private and protected in Python?
sobes.tech AI
Answer from AI
Python does not have strict privacy for methods like some other languages. However, there are conventions:
-
Methods starting with a single underscore (
_method) are considered "protected" by convention. This means they are intended for use within the class and its subclasses, but are technically accessible from outside. -
Methods starting with double underscores (
__method) undergo name mangling — their names are changed by the interpreter to make external access more difficult. This approaches "private" methods, although access cannot be fully restricted.
Example:
class MyClass:
def _protected_method(self):
print("This is a protected method")
def __private_method(self):
print("This is a private method")
obj = MyClass()
obj._protected_method() # Works, but not recommended to call from outside
# obj.__private_method() # AttributeError
obj._MyClass__private_method() # Can be called via name mangling
Thus, the main difference is the level of "concealment" and access conventions, not strict enforcement.