Home Backend Development Python Tutorial Python single underline/double underline usage summary

Python single underline/double underline usage summary

Dec 08, 2016 am 11:17 AM
python

Python uses underscores as variable prefixes and suffixes to specify special variables/methods.

There are mainly four situations
1. 1. object # public
2. __object__ # special, python system use, user should not define like it
3. __object # private (name mangling during runtime)
4. _object # obey python coding convention, consider it as private
Core style: avoid using an underscore as the beginning of a variable name.

Because the underscore has special meaning to the interpreter and is the symbol used by built-in identifiers, we recommend that programmers avoid using an underscore as the beginning of variable names. Generally speaking, the variable name _object is considered "private" and cannot be used outside the module or class, and cannot be imported using 'from moduleimport *'. When the variable is private, it is a good practice to use _object to represent the variable. Because the variable name __object__ has a special meaning to Python, this naming style should be avoided for ordinary variables.

Python’s description of private, there is no concept of protected in python, it is either public or private, but private in python is not like C++, Java, it is not private in the true sense, through name mangling (name adaptation (The purpose is to prevent subclasses from accidentally overriding the methods or attributes of the base class), that is, by adding a "single underscore" + class name in front, eg: _Class__object) mechanism to access private.

 The member variables starting with "single underscore" are called protected variables, which means that only class objects and subclass objects themselves can access these variables; the ones starting with "double underscore" are private members, which means that only the class object itself can access them. Subclass objects cannot access this data either. (As shown below)
Starting with a single underscore (_foo) represents class attributes that cannot be accessed directly. They need to be accessed through the interface provided by the class and cannot be imported using "from xxx import *"; those starting with a double underscore (__foo ) represents the private members of the class; (__foo__) starting and ending with double underscores represents the special method-specific identification in Python, such as __init__() representing the constructor of the class.

1.class Foo():

2. def __init__():
3. ...
4.
5. def public_method():
6. print 'This is public method'
7.
8 . DEF __FULLPRIVATE_METHOD ():
9. Print 'this is double underscore lead method'
10.
11. UNDERSCORE Leading Method '
An object of instantiated FOO,

1. f = Foo()
1. f.public_method() # OK
2.
3. f.__fullprivate_method() # Error occur
4.
5. f._halfprivate_method() # OK
6.
7 .                                                                                                                                                                                                                                                          . However, according to the convention of python, they should be regarded as private and should not be used externally (if you have to use them, there is no way). Good programming practice is not to use them externally. At the same time, according to the Python docs, the scope of _object and __object is limited to this module.

================================================== ==============================
Understand the Python naming mechanism (starting with single and double underscores) (Reprinted: http://blog. csdn.net/lanphaday)
Introduction
I warmly invite everyone to guess the output of the following program:
class A(object):
  def __init__(self):
self.__private()
self.public()
Def __private (self):
Print 'a .__ Private ()'
def Public (SELF):
Print 'A.Public ()'
Class b (a):
def __private (seld):
Print 'B.__ Private ()'
def public(self):
print 'B.public()'
b = B()
First exploration
The correct answer is:
A.__private()
B.public()
If you have already guessed it correctly, you don’t need to read this blog post of mine . If you didn’t guess correctly or have questions in your mind, then this blog post of mine is just for you.
Everything starts with why "A.__private()" is output. But to explain why, we need to understand Python's naming mechanism.
According to the Python manual, a variable name (identifier) ​​is an atomic element of Python. When a variable name is bound to an object, the variable name refers to the object, just like in human society, right? When a variable name appears in a code block, it is a local variable; when a variable name appears in a module, it is a global variable. I believe everyone has a good understanding of modules, but code blocks may be a little confusing. Explain here:
A code block is a piece of Python program text that can be used as an executable unit; modules, function bodies, and class definitions are all code blocks. Not only that, every interactive script command is also a code block; a script file is also a code block; and a command line script is also a code block.
Next, let’s talk about the visibility of variables. We introduce the concept of scope. Scope is the visibility of the variable name within the code block. If a local variable is defined in a code block, the scope includes this code block. If a variable is defined in a function code block, the scope extends to any code block in the function block, unless another variable with the same name is defined there. However, the scope of variables defined in a class is limited to the class code block and will not extend to the method code block.
Mistake
According to the theory in the previous section, we can divide the code into three code blocks: the definition of class A, the definition of class B and the definition of variable b. According to the class definition, we know that the code defines three member variables for class A (Python's functions are also objects, so it works if the member methods are called member variables.); class B defines two member variables. This can be verified by the following code:
>>> print 'n'.join(dir(A))
_A__private
__init__
public
>>> print 'n'.join(dir(B) )
_A__private
_B__private
__init__
public
Hey, why does class A have an Attribute named _A__private? And __private disappeared! This is about talking about Python's private variable suppression.
Explore
Friends who know Python know that Python treats variables that start with two or more underscore characters and do not end with two or more underscore characters as private variables. Private variables are converted to long form (made public) before code generation. The conversion mechanism is like this: insert the class name at the front of the variable, and then add an underscore character at the front. This is called private name mangling. For example, the __private identifier in class A will be converted to _A__private, which is why _A__private and __private disappeared in the previous section.
Two more digressions:
First, because rolling will make the identifier longer. When it exceeds 255, Python will cut it off. Pay attention to the naming conflicts caused by this.
Second, when the class names are all named with underscores, Python will no longer perform rolling. Such as: & & gt; & gt; & gt; class ____ (object):
DEF __init __ (Self):
Self .______MEF __METHOD (SELF):
Print '_____ Method ()' & & GT. ; & gt; & gt ; print 'n'.join(dir(____))
__class__
__delattr__
__dict__
__doc__
__getattribute__
__hash__
__init__
__method
__reduce__
__reduce_ex__
__repr__
__setattr__
__str__
__weakref__
>>> obj = ____()
____.__method()
>>> obj.__method() # Can be called externally
____.__method()
Now let’s go back and see why Output "A.__private()"!
The truth
I believe smart readers have guessed the answer by now, right? If you haven't thought of it yet, let me give you a hint: the truth is similar to macro preprocessing in C language.
Because class A defines a private member function (variable), private variable squeezing is performed before code generation (notice the line marked in red in the previous section?). After rolling, the code of class A becomes like this:
class A(object):
def __init__(self):
                                                                                                                                                                                                                                                                                                                                                                                                             - – print away ;
Because the __init__ method was not overridden when class B was defined, A.__init__ is still called, that is, self._A__private() is executed, and "A.__private()" is naturally output.
The following two pieces of code can increase persuasion and enhance understanding:
>>> class C(A):
        def __init__(self):                # Rewrite __init__, no longer call self._A__private
              self.__private ()                                                                                                                                                                                            print 'C.public()'
> ;>> c = C()
C.__private()
C.public()
######################### #
> def __private(self):
                                                                                                                                                                                                                                      __private(self),            ​.public()

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles