Middle
What is the difference between the parameters _value and __value in Python?
sobes.tech AI
Answer from AI
In Python, _value and __value are naming conventions, not strict visibility rules.
-
_value(single underscore): Indicates that the variable or method is "internal" or "protected". It is a convention that they should not be accessed directly outside the class or module. -
__value(double underscore): Triggers name mangling. Python automatically changes the name of the variable or method to_ClassName__valueto avoid conflicts in inheritance hierarchies. It does not make the variable fully private, but makes accidental access more difficult and helps avoid name clashes.
Summary: _value — convention for "protected" members; __value — name mangling to prevent name conflicts in inheritance.
class MyClass:
def __init__(self):
self._protected_value = 10 # Protected by convention
self.__private_value = 20 # Name mangled
obj = MyClass()
print(obj._protected_value) # Accessible but discouraged
# print(obj.__private_value) # AttributeError
print(obj._MyClass__private_value) # Access via mangled name