Junior — Middle
What is the role of using underscores in method names in Python?
sobes.tech AI
Answer from AI
In Python, underscores in method and variable names are used to indicate access level and special properties:
- Single underscore at the beginning (_method) — a convention indicating that the method or attribute is "protected", intended for internal use within the class or module, but not strictly private.
- Double underscore at the beginning (__method) — triggers name mangling, making it harder to access the method or attribute from outside the class, thus making it more private.
- Underscore at the end (method_) — used to avoid conflicts with Python keywords.
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() # Can be called, but by convention not recommended
# obj.__private_method() # Error, method not directly accessible
Underscores are a convention to indicate intended access level, but do not enforce it.