Understanding Python's double underline naming

Source: Internet
Author: User
Tags class definition

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# not crushed__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 ()"! TruthBelieve 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 ()# The line has changed #Self.public () def _a__private (self):# This is a change in the line #print ' A.__private () ' Def public: 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 ()# It's bound to be _c_private Self.public () def __private (self): print ' C.__private () ' Def public: print ' C. Public () ' >>> C = C () c.__private () c.public () ############################>>> class A (object): Def __ Init__ (self): Self._a__private ()# Call a function without a definition, Python will give it to me Self.public () def __private (self): print ' A.__private () ' Def public: print ' A. Public () ' >>>a = A () a.__private () A.public ()

Understanding Python's double underline naming

Related Article

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.