Delving into Python's Single and Double Underscores
Python's use of leading underscores before object names conveys specific meanings and behaviors.
Single Underscore: "Internal Use" Indicator
A single underscore indicates that an attribute or method is intended for use within its own class. It's a convention, not an enforced rule, to discourage external access. Additionally, when a single underscore precedes function names in a module, it implies they should not be imported from outside the module.
Double Underscores: Name Mangling
Double underscores trigger name mangling, a process where the identifier becomes prefixed with the class name with leading underscores removed. This is done for "private" class members to avoid conflicts with members of derived classes or external code. However, it's important to note that determined users can still access these variables.
Example:
In the following example, __superprivate is intended to be inaccessible outside the class, while _semiprivate follows the convention for internal use:
class MyClass: def __init__(self): self.__superprivate = "Hello" self._semiprivate = ", world!"
When accessing these members outside the class, only _semiprivate will be exposed:
mc = MyClass() print(mc._semiprivate) # "Hello" print(mc.superprivate) # Attribute error
Therefore, single underscores indicate intended internal use, while double underscores protect members from direct access by name mangling, providing a privacy layer but not absolute security.
The above is the detailed content of What's the Difference Between Single and Double Underscores in Python?. For more information, please follow other related articles on the PHP Chinese website!