PYTHON Specifies special variables/methods using underscores as variable prefixes and suffixes.
There are four main cases
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 Coding Convention, consider it as private
Core style: Avoid using underscores as the start of variable names .
Because underscores have special meanings for the interpreter and are symbols used by the built-in, we recommend that you avoid using underscores as the starting point for variable names. in general, variable name _object is considered "private" and cannot be used outside of a module or class, and cannot be imported with ' from Moduleimport * '. When a variable is private, it is good practice to use _object to represent variables. Because the variable name __object__ has a special meaning for Python, this naming style should be avoided for common variables.
There is no concept of protected in Python, either public or private, but private in Python, unlike C + +, Java, is not really private, by name Mangling (The purpose is to prevent subclasses from accidentally overriding the base class's methods or properties), i.e., the "single underscore" + Class name, eg:_class__object) mechanism to access the private.
A member variable that starts with a "single underline" is called a protection variable, meaning that only class objects and subclass objects can access these variables themselves;
A "double underline" begins with a private member, meaning that only the class object can access it, and the child object cannot access the data. (as shown below)
A class attribute that begins with a single underscore (_foo) cannot be accessed directly, and is accessed through the interface provided by the class and cannot be imported with "from XXX import *";
A double underscore (__foo) represents a private member of a class;
The __foo__, which begins with a double underscore , represents a special method-specific identifier, such as __init__ (), which represents the construction of the class . 1.class Foo ():
2. Def __init__ ():
3 .....
4.
5. Def public_method ():
6. Print ' This was public method '
7.
8. Def __fullprivate_method ():
9. Print ' This is underscore leading method '
.
One by one .Def _halfprivate_method ():
.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
As can be seen from the above example, F._halfprivate_method () can be accessed directly, indeed. But according toConvention, it should be treated as private rather than used externally (if you have to use it), good habits are not to use it externally. Also, according to Python docs, the scope of _object and __object is limited within this module.
Quote an article from someone else
Understanding the python naming mechanismThis article was originally published in the blog (http://blog.csdn.net/lanphaday) of flower butterflies, and is welcome to be reproduced, but must be retained and not used for commercial purposes. Thank you.
IntroI warmly invite you to guess the output of this 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 (self): print ' B.__private () ' Def public: print ' b.public () ' b = B ()
Preliminary studyThe correct answer is:a.__private ()b.public ()If you have guessed right, then you can not read my blog post. If you have not guessed right or have doubts in your mind, then my this piece of Bo Wenzheng is for you to prepare. It all starts with the output of "a.__private ()". But to make it clear why, it is necessary to understand the naming mechanism of Python. 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 the object, just like human society, isn't it? When the variable name appears in the code block, it is a local variable, and when the variable name appears in the module, it is the global variable. The module believes everyone has a good understanding, but the code block may be confusing. Here's an explanation: a block of code is a Python program text that can be used as an executable unit, and modules, function bodies, and class definitions are blocks of code. Not only that, each interactive script command is also a block of code; a script file is also a block of code; a command-line script is also a block of code. Next we talk about the visibility of variables, and we introduce a concept of scope. The scope is the visibility of the variable name in the code block. If a local variable is defined in a code block, the range includes this block of code. If a variable is defined in a function code block, that range extends to any block of code in the function block unless it defines another variable with the same name. However, the scope of a variable defined in a class is scoped to the class code block, not to the method code block.
MysteryAccording to the theory of 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 (the Python function is also an object, so the member method is called a member variable, which also makes sense.) ), 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 Gee, why does Class A have a Attribute called _a__private? And __private's gone! This is about Python's private variable rolling.
ExploreA friend of Python knows that Python treats a variable that begins with two or an underscore character and does not end in two or an underscore as a private variable. Private variables are converted to long-form (public) before the code is generated. The conversion mechanism is this: Insert the class name at the front of the variable, and then add an underscore character to the front end. This is known as private variable rolling (private name mangling). The __private identifier in class A will be converted to _a__private, which is why the _a__private and __private disappeared in the previous section. Another two-point digression: First, because the pressure will make the identifier longer, when more than 255, Python will be cut off, pay attention to the resulting naming conflicts. The second is that when the class name is all underlined, Python no longer performs a rolling. such as:>>> class ____ (object): def __init__ (self): Self.__method () def __method (self): print ' ____.__method () ' >> > print '/n '. Join (dir (___)) __class____delattr____dict____doc____getattribute____hash____init____method # is not crimped __module_ ___new____reduce____reduce_ex____repr____setattr____str____weakref__>>> obj = ____ () ____.__method () > >> obj. __method () # can call ____.__method externally () Now let's look back and see why the output is "a.__ Private () "It!"
Truth Believe that the smart reader has guessed the answer now? If you haven't thought about it, I'll give you a hint: the truth is similar to the macro preprocessing in C. Because Class A defines a private member function (variable), the private variable rolling is performed before the code is generated (notice the line of the previous section marked red?). )。 After rolling, the code for Class A becomes this: Class A (object): def __init__ (self): self._a__private () # This line has changed Self.public () def _a__private (self): # the line has changed print ' a.__private () ' def public (self): print ' a.public () ' Is it a bit like a macro expansion in C? Because the __init__ method is not overwritten when the class B is defined, the call is still a.__init__, that is, the self._a__private () is executed, and the natural output is "a.__private ()". The following two sections of code can increase persuasion and improve understanding:>>> class C (A): def __init__ (self): # Rewrite __init__ , no longer call self._A__private self.__private () # The _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 undefinedThe function, python will give it to me ^_^ ~ Self.public () def __private (self): print ' a.__private () ' def public ( Self): print ' a.public () ' >>>a = A () A.__private () A.public ()
Go Python underline and the meaning of namespaces