Home > Backend Development > Python Tutorial > How Do Single and Double Underscores Affect Variable and Method Visibility in Python?

How Do Single and Double Underscores Affect Variable and Method Visibility in Python?

Patricia Arquette
Release: 2024-12-22 08:19:09
Original
800 people have browsed it

How Do Single and Double Underscores Affect Variable and Method Visibility in Python?

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!"
Copy after login
  • __superprivate is a truly private variable, accessible only within the MyClass instance and cannot be accessed directly from outside.
  • _semiprivate is conventionally private but can be accessed directly.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template