What is the difference between a single underscore and a double underscore in Python?
Answer from AI
sobes.tech AI
An underscore (_) in Python has several uses:
- Traditionally used to denote "internal" or "private" attributes and methods of classes. This is a convention for developers, not a strict interpreter rule.
- Used in the Python interpreter's interactive session to store the result of the last executed expression.
- Used in a
forloop or assignment to indicate a variable whose value will not be used. - Used in internationalization (
gettext).
Double underscore (__) in Python is used for:
-
Name mangling: Used to create "semi-private" class attributes and methods. The Python interpreter changes the name of such an attribute by adding
_ClassNameat the beginning, making it more difficult to access from outside the class.class MyClass: def __init__(self): self.__private_var = 10 def public_method(self): print(self.__private_var) obj = MyClass() # Direct access attempt will raise AttributeError # print(obj.__private_var) # Access via mangling print(obj._MyClass__private_var) -
"Dunder" methods (Magic methods): Special methods starting and ending with double underscores (e.g.,
__init__,__str__,__add__) that are called during specific operations (object initialization, string conversion, addition, etc.).
Comparison:
| Feature | Single underscore (_) |
Double underscore (__) |
|---|---|---|
| Purpose | Convention to denote internal elements; temporary storage; ignore variable; internationalization. | Name mangling (for "semi-private" class elements); "dunder" methods. |
| Interpreter handling | Interpreter does not perform special handling of the name. | Interpreter performs name mangling for class attribute and method names starting with __ (without trailing __). |
| Access from outside the class | Direct access is possible. | Direct access is hindered due to name mangling. Access via _ClassName__name. |
Thus, the main difference is that double underscore triggers the name mangling mechanism by the interpreter for class attributes and methods, while a single underscore is more of a naming convention that does not directly affect interpreter behavior (except in the interactive shell and internationalization).