Python single underline/double underline usage Summary

Source: Internet
Author: User
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 Python 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 built-in identifiers, we recommend that programmers 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.

Python's description of private, there is no concept of protected in Python, either public or private, but the private in Python is not like C + +, Java, it is not the real sense of private , by name Mangling (The purpose is to prevent subclasses from accidentally overriding the base class's methods or properties), which is preceded by 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; "Double underscore" begins with a private member, meaning that only the class object can access it, and even the subclass 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, cannot be imported with a "from XXX import *", and a double underscore (__foo) represents a private member of the class; A double underscore that starts and ends (__foo__ Represents a special method-specific identifier for Python, such as __init__ (), which represents the constructor of a 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 double underscore leading method '
10.
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. However, according to Python's convention, it should be treated as private rather than used externally (if you have to use it), good programming habits are not used externally. Also, according to Python docs, the scope of _object and __object is limited within this module.

==============================================================================
Understanding the Python naming mechanism (single-double Underline) (reprinted: 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 (A):
def __private (self):
print ' b.__private () '
def public (self):
print ' B.public () '
b = B ()
Of
The 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 a little bit of explanation:
A block of code is a Python program text that can be used as an executable unit, and a module, a function body, and a class definition 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.
Mystery
According 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 named _a__private? And __private's gone! This is about Python's private variable rolling.
Explore
A 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.
Let's talk about the two-point topic:
One is 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 # has not been 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 ()"!
The 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 is the same line.
Self.public ()
def _a__private (self): # This line has changed.
print ' a.__private () '
def public (self):
print ' A.public () '
Is it a bit like the macro expansion in C language?
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 pieces of code can increase persuasion and improve understanding:
>>> class C (A):
def __init__ (self): # rewrite __init__, no longer calls Self._a__private
Self.__private () # It's bound to be _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 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 ()
A.__private ()
A.public ()
  • 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.