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

Python single underline/double underline usage summary

巴扎黑
Release: 2016-12-08 11:17:59
Original
1906 people have browsed it

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()

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template