Home > Backend Development > Python Tutorial > What's the Difference Between Single and Double Underscores in Python?

What's the Difference Between Single and Double Underscores in Python?

Linda Hamilton
Release: 2024-12-22 12:07:41
Original
955 people have browsed it

What's the Difference Between Single and Double Underscores in Python?

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!"
Copy after login

When accessing these members outside the class, only _semiprivate will be exposed:

mc = MyClass()
print(mc._semiprivate)  # "Hello"
print(mc.superprivate)  # Attribute error
Copy after login

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!

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