Junior — Middle
Explain the differences in using a single and double underscore in variable and method names in Python.
sobes.tech AI
Answer from AI
In Python, a single underscore at the beginning of a variable or method name (e.g., _var) is a convention indicating that this name is intended for internal use (protected) and should not be used outside the class or module. It is just a recommendation; the interpreter does not prohibit access.
A double underscore at the beginning of a name (e.g., __var) activates the name mangling mechanism — the name of the variable or method is changed by the interpreter to make external access more difficult. This is used to create private attributes that are hard to override or accidentally use in subclasses.
Example:
class MyClass:
def __init__(self):
self._protected = 1 # convention: protected attribute
self.__private = 2 # name mangling
obj = MyClass()
print(obj._protected) # access is possible but not recommended
# print(obj.__private) # will raise AttributeError
print(obj._MyClass__private) # access to the "private" attribute via name mangling
Thus, a single underscore is a convention, and a double underscore is a name hiding mechanism.