Understanding Python's double underline naming

Source: Internet
Author: User
Tags class definition visibility

Add by Zhj: Today when learning the source code of Simplehttpserver, we see a baseserver class in the Python standard library socketserver module, the __init__ method of the class is defined as follows

    def __init__ (self, server_address, requesthandlerclass):         """ Constructor.  May is extended, do not override. """          = server_address        = requesthandlerclass self        . __is_shut_down = Threading. Event () Self        . __shutdown_request = False

The comment that reads it says that the class cannot be override. At initialization, it defines the two variables of __is_shut_down and __shutdown_request, which I have not understood before about the meaning of variables such as __XX,

Now Lenovo can not be this variable cannot quilt class override it? And then found the following article, sure enough. Python has taken this private variable into account from the interpreter level, guaranteeing this

Variables are not covered by the same name variable in the quilt class, so it is not necessary for the subclass to define the __XX variable with the same name, because even if it is defined, it cannot overwrite the variable with the same name in the parent class.

And it's so easy to read that it's so confusing that people get confused. Python This trick is doing quite well. In fact, before the meaning of the __xx variable is also understood, but at that time only to think about how it works, not

Understand what it is for, and think about it: then, before putting the cart before the horse, if you know the purpose of this, then understand the principle is easier.

Original: Not Found

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 the 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 be called Externally ____.__method () Now let's look back and see why the output is "a.__private ()"! 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 calls  self._A__private              self. __private ()        #  binding here is  _C_private               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 a function that is not defined, python  will give it to me &Nbsp;              self.public ()         def __private (self):              print ' a.__private () '        def public (self):              print ' a.public () ' >>>a = A () a.__private () A.public ()

Understanding Python's double underscore name (go)

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.