Python uses underlines as the prefix and suffix of variables to specify special variable methods. There are four main situations: 1.1.object # public2. _ object __# special, pythonsystemuse, usershouldnotdefine... Python uses underscores as the prefix and suffix of variables to specify special variables/methods.
There are four main scenarios
1. 1. object # public
2. _ object _ # special, python system use, user shocould 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 underscores as the start of variable names.
Because underlines have special meanings for the interpreter and are symbols used by built-in identifiers, we recommend that programmers avoid using underscores as the beginning of the variable name. Generally, the variable name_object is regarded as "private" and cannot be used outside the module or class. it cannot be imported using 'from moduleimport. When the variable is private, it is a good habit to use _ object to represent the variable. Because the variable name__ object _ has special meanings for Python, this naming style should be avoided for common variables.
The description of private in python. The concept of protected does not exist in python. it is either public or private, but private in python is not like C ++ or Java, it is not actually private. it is adapted by name mangling (to prevent the subclass from accidentally overwriting the methods or attributes of the base class ), that is, you can access private by adding the "single underline" + Class name, eg: _ Class _ object.
A member variable starting with "single underline" is called a protection variable, meaning that only the class object and the subclass object can access these variables themselves. "double underline" begins with a private member, this means that only the class object can access this data, and even the subclass object cannot access this data. (As shown below)
A class attribute that starts with a single underscore (_ foo) represents a class attribute that cannot be accessed directly. it must be accessed through the interface provided by the class. it cannot be imported using "from xxx import; (_ foo) starting with a double underline represents a private member of the class; (_ foo _) starting with and ending with a double underline represents a special identifier for special methods in python, for example, _ init _ () indicates 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 leading method'
10.
11. def _ halfprivate_method ():
12. print 'This is one underscore leading method'
Instantiate an object of Foo,
1. f = Foo ()
1. f. public_method () # OK
2.
3. f. _ fullprivate_method () # Error occur
4.
5. f. _ halfprivate_method () # OK
6.
7. f. _ Foo _ fullprivate () _ method () # OK
From the above example, we can see that f. _ halfprivate_method () can be accessed directly, indeed. However, according to the python conventions, it should be regarded as private instead of using them externally (if you have to use them). a good programming habit is not to use it externally. In addition, according to the description of Python docs, the _ object and _ object scopes are limited in this module.
========================================================== ==============================================
Understanding the Python naming mechanism (starting with a single double underline) (reproduced: http://blog.csdn.net/lanphaday)
Introduction
I warmly invite you 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 ():
Def _ private (self ):
Print 'B. _ private ()'
Def public (self ):
Print 'B. public ()'
B = B ()
Preliminary exploration
The correct answer is:
A. _ private ()
B. public ()
If you have guessed it, you can skip this blog. If you haven't guessed it or have some questions, I have prepared this blog for you.
The reason for the output is "A. _ private. But to clarify why, we need to understand the Python naming mechanism.
According to Python manual, the variable name (identifier) is an atomic element of Python. When a variable name is bound to an object, the variable name refers to this object, just like in human society, isn't it? When the variable name appears in the code block, it is the local variable; when the variable name appears in the module, it is the global variable. I believe everyone has a good understanding of the module, but the code block may be confusing. Here we will explain:
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. In addition, each 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 we will talk about the visibility of variables. we will introduce the concept of a range. The range is the visibility of variable names in the code block. If a code block defines local variables, the range includes this code block. If a variable is defined in a function code block, the range is extended to any code block in the function block unless another variable with the same name is defined. But the scope of variables defined in the class is limited to the class code block, instead of being extended to the method code block.
Lost
According to the theory above, we can divide the code into three code blocks: Class A, Class B, and variable B. According to the class definition, we know that the code defines three member variables for Class A (Python functions are also objects, so the Member methods can also be called member variables .); Class B defines two member variables. This can be verified by the following code:
>>> Print '\ n'. join (dir ())
_ A _ private
_ Init __
Public
>>> Print '\ n'. join (dir (B ))
_ A _ private
_ B _ private
_ Init __
Public
Why does Class A have an Attribute named _ A _ private? And _ private disappears! Now let's talk about the rolling of Python's private variables.
Exploration
Anyone familiar with Python knows that Python treats a variable that starts with two or more underscores and does not end with two or more underscores as a private variable. Private variables are converted to long format (public) before code generation ). The conversion mechanism is as follows: Insert the class name at the front end of the variable, and add an underline character at the front end. This is the so-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 disappear in the previous section.
Let's talk about two more things:
First, the identifier is longer due to rolling. when it exceeds 255, Python will cut off. Note the naming conflict caused by this.
Second, when all the class names are named below, Python will not execute rolling. For example:
>>> Class ____ (object ):
Def _ init _ (self ):
Self. _ method ()
Def _ method (self ):
Print '____. _ method ()'
>>> Print '\ n'. join (dir (____))
_ Class __
_ Delattr __
_ Dict __
_ Doc __
_ Getattribute __
_ Hash __
_ Init __
_ Method # Not rolled
_ Module __
_ New __
_ Reduce __
_ Performance_ex __
_ Repr __
_ Setattr __
_ Str __
_ Weakref __
>>> Obj = ____()
____. _ Method ()
>>> Obj. _ method () # can be called externally
____. _ Method ()
Now let's look at why "A. _ private ()" is output!
Truth
I believe that smart readers have already guessed the answer? If you haven't thought of it, I will give you a prompt: The truth is similar to macro preprocessing in C language.
Because Class A defines A private member function (variable), execute the private variable rolling before the code is generated (note that the line marked with red in the previous section does not exist ?). After the rolling, the code of Class A becomes like this:
Class A (object ):
Def _ init _ (self ):
Self. _ A _ private () # This line has changed
Self. public ()
Def _ A _ private (self): # This line has also changed
Print 'A. _ private ()'
Def public (self ):
Print 'A. public ()'
Is it a bit like the macro development in C language?
Because the _ init _ method is not overwritten when class B is defined, the call is still. _ init __, that is, self. _ A _ private (), which naturally outputs ". _ private.
The following two sections of code increase persuasiveness and increase understanding:
>>> Class C ():
Def _ init _ (self): # Rewrite _ init _, no longer calling self. _ A _ private
Self. _ private () # _ C_private is bound here.
Self. public ()
Def _ private (self ):
Print 'C. _ private ()'
Def public (self ):
Print 'C. public ()'
>>> C = C ()
C. _ private ()
C. public ()
############################
>>> Class A (object ):
Def _ init _ (self ):
Self. _ A _ private () # call an undefined function. Python will give it to me
Self. public ()
Def _ private (self ):
Print 'A. _ private ()'
Def public (self ):
Print 'A. public ()'
>>> A = ()
A. _ private ()
A. public ()
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.