Unmasking the Underscore: Understanding Single and Double Underscore in Python
In Python, the presence of one or two leading underscores before an identifier can alter its meaning and visibility within a class or module.
Single Underscore: Internal Usage Indicator
A leading underscore signifies that an attribute or method is intended for internal use within the current class. However, this is merely a convention; privacy is not enforced. Additionally, single leading underscores in module functions indicate that they should not be imported by external modules.
Double Underscore: Name Mangling
Two leading underscores signify name mangling. These identifiers are transformed internally with a ClassName prepended, where ClassName is the current class name with leading underscores removed. This mechanism allows the definition of class-private instance and class variables and provides some protection against external access. However, it's important to note that name mangling does not guarantee absolute privacy, as determined individuals can still access private variables.
Example:
Consider the following class:
class MyClass(): def __init__(self): self.__superprivate = "Hello" self._semiprivate = ", world!"
As demonstrated in the example output, accessing __superprivate directly results in an AttributeError, while _semiprivate can be accessed.
The __dict__ attribute reveals the existence of both __superprivate and _semiprivate as mangled, confirming the name mangling mechanism.
The above is the detailed content of How Do Single and Double Underscores Affect Variable and Method Visibility in Python?. For more information, please follow other related articles on the PHP Chinese website!