Explain the underline naming rules in Python

Source: Internet
Author: User

in Python, the underline naming rules tend to make beginners quite doubts: Single underline, double underline, double underline also points before and after ... What is the difference between their role and the use of the scene ? Let's talk about this topic today.

1. Single Underline (_) Typically, a single underscore (_) is used in the following 3 scenarios:
1.1 in the interpreter:

in this case, "_" represents the result of the statement executed on the previous line in the interactive interpreter session. This usage is first used by the standard CPython interpreter, and then other types of interpreters are used successively.

>>> _ Traceback (most recent): File "<stdin>", line 1, in <module> nameerror:name ' _ ' is n OT defined >>> 42>>> _ 42>>> ' alright! ' if _ Else ':(' alright! ' >>> _ ' alright! '
1.2 as a name:

this is slightly related to the above point, where "_" is used as a temporary name. This way, when someone reads your code, you'll know that you've assigned a specific name, but you won't be using that name again later. For example, in the following example, you might not be interested in the actual values in the loop count, and you can use "_" at this point.

n = 42for _ in range (n):     do_something ()
1.3 Internationalization:

Perhaps you have also seen that "_" is used as a function. In this case, it is commonly used to implement the function name of the translation lookup between internationalized and localized strings, which appears to originate from and follow the corresponding C convention. For example, in the "Transformations" section of the Django document , you would see the following code:

From django.utils.translation import Ugettext as _ from django.http import HttpResponse def my_view (request):     output = _ ("Welcome to My Site.")     return HttpResponse (Output)
It can be found that the use of Scenario II and scenario three may conflict with each other, so we need to avoid using "_" as a temporary name in a block of code that uses "_" as the Internationalization Lookup transformation feature. 2, the name of the single underline (such as: _shahriar) The programmer uses a single underscore before the name to specify that the Name property is "private". This is a bit like convention, and in order for others (or yourself) to use the code, you will know that names that begin with "_" are for internal use only. As described in the Python documentation:
The name prefixed by the underscore "_" (for example, _spam) should be considered a non-exposed part of the API (whether it is a function, method, or data member). At this point, you should think of them as an implementation detail that requires no external notification when modifying them.
As mentioned above, this is really similar to a convention, because it does have a certain meaning to the interpreter, if you write the code "from < module/package name > Import *", then the name beginning with "_" will not be imported, unless the module or package "__all_ _ "list explicitly contains them . For more information, see " importing * in Python ".
It is worth noting, however, that if you import a module using Import A_module, you can still access such an object in the form of A_module._some_var.

In addition, a single underline at the beginning of the general situation is not used in the case of an extension library written with a C is sometimes named after an underscore, and then use a stripped-down Python module for packaging. The module, such as struct, is actually a Python wrapper for the C module _STRUCT.

3. Double underline before name (eg: __shahriar) the use of a name (specifically a method name) before the double underscore (__) is not a convention, and it has a specific meaning for the interpreter. This usage in Python is intended to avoid conflicting names defined by subclasses. The Python document states that any identifier for the form "__spam" ( at least two leading underscores, up to one subsequent underscore) will be replaced by the "_classname__spam" form, where "classname" is the current class name with the leading underscore removed. For example, the following example:
>>> class A (object): ...     def _internal_use (self): ...         Pass ...     def __method_name (self): ...         Pass ... >>> dir (A ()) [' _a__method_name ', ..., ' _internal_use ']
as expected, "_internal_use" has not changed, and "__method_name" has been turned into "_classname__method_name": __ begins of the 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 called a private variable. name Adaptation (Private name mangling) . at this point, if you create a subclass B of a, you won't be able to easily overwrite the method "__method_name" in A,
>>> class B (A): ...     def __method_name (self): ...         Pass ... >>> dir (B ()) [' _a__method_name ', ' _b__method_name ', ..., ' _internal_use ']
However, if you know the pattern, you will eventually be able to access the "private" variable.
The private variable name adaptation is intended to give a simple way to define "private" instance variables and methods in a class, to avoid problems with the definition of instance variables for derived classes, or to confuse variables in external code.
It is important to note that obfuscation rules (private variable name adaptation) are primarily intended to avoid accidental errors, which are still possible to be accessed or modified (using _classname__membername), and are useful in certain situations, such as debugging.

These functions are almost identical to the final methods in Java and Standard methods in C + + classes (not virtual methods).

Let's talk about the two-point topic:
one is because the rolling (adaptation) 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 will no longer perform a rolling (adaptation).

Whether it is a single underscore or a double-underlined member, it is hoped that external program developers do not directly use these member variables and these member functions, but the double underscore syntax can be more directly to avoid the wrong use, but if the _ Class name __ Member name can still be accessed. A single underline may be handy for dynamic debugging, so it might be better to use a single underline as long as the members of the project group are not directly using the member that starts with the underscore.

4. Double underline before and after name (for example: __init__) this usage represents a special method name in Python. In fact, this is only a convention for Python systems, which will ensure that there is no user-defined name conflict. Typically, you will overwrite these methods and implement the functions you need in order for Python to invoke them. For example, when you define a class, you often overwrite the "__init__" method.

Double underscore the end of the double underline is some Python "magic" objects, such as the __init__ of class members, __del__, __add__, __getitem__, etc., as well as the global __file__, __name__, and so on. The official Python recommendation never apply such a naming method to your own variables or functions, but use them as documented instructions. Although you can also write your own special method name, do not do so.

>>> class C (object): ...     def __mine__ (self): ...         Pass ... >>> dir (C) ... [..., ' __mine__ ', ...]
In fact, it's easy to get rid of this type of naming, and just let Python define special names to follow this convention:) 5, off-topic if __name__ = = "__main__":

all Python modules are objects and have a few useful properties that you can use to easily test the modules you write.

The module is an object, and all modules have a built-in property of __name__. The value of the __name__ of a module depends on how you apply the module. If the import module, then the value of __name__ is usually the file name of the module, without the path or file extension. But you can also run the module directly like a standard program, in which case the value of __name__ will be a special default value: __main__.

>>> import odbchelper>>> odbchelper.__name__ ' Odbchelper '

Once you understand this, you can design a test suite for your module within the module to include the IF statement. When you run the module directly, the value of __name__ is __main__, so the test suite executes. When you import a module, the value of __name__ is something else, so the test suite is ignored. This makes it much easier to develop and debug a new module before it is integrated into a large program.
On Macpython, an additional step is required to make the if __name__ technique effective. Click on the black triangle in the upper right corner of the window to pop up the module's Properties menu and confirm that Run as __main__ is selected.

6. Summary:

Python Specifies special variables with underscores as variable prefixes and suffixes.
_xxx cannot be imported with ' from module import * '
__xxx__ System Definition name
private variable names in the __xxx class
Core style: Avoid using underscores as the beginning 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 beginning of variable names. In general, variable name _xxx is considered "private" and cannot be used outside of a module or class. When a variable is private, it is good practice to use _xxx to represent variables. because the variable name __xxx__ has a special meaning for Python, this naming style should be avoided for common variables.
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.
A class attribute that begins with a single underscore (such as _foo) that is not directly accessible by the Class property, is accessed through the interface provided by the classes, cannot be imported with a "from XXX import *", or a double underscore (such as __foo) represents a private member of a class, preceded and terminated with a double underscore (__ FOO__) Represents a special method-specific identifier for Python, such as __init__ (), which represents the constructor of a class.

PEP Specification:

pep-0008:in addition, the following special forms using leading or trailing underscores is recognized (these can generall Y is combined with any case convention):    -_single_leading_underscore:weak ' internal use ' indicator. e.g. ' from M import * ' does not import objects whose name starts with an underscore.    -Single_trailing_underscore_: Used by convention to avoid conflicts with Python keyword, e.g.      Tkinter.toplevel (maste R, class_= ' ClassName ')    -__double_leading_underscore:when Naming a class attribute, invokes name mangling (inside CLA SS FooBar, __boo becomes _foobar__boo; See below).    -__double_leading_and_trailing_underscore__: "Magic" objects or attributes that live in user-controlled namespaces. e.g. __init__,      __import__ or __file__. Never invent such names; Only use them as documented.
7, Refer:

[1] importing ' * ' in Python

Http://shahriar.svbtle.com/importing-star-in-python

[2] Understanding Python's double underline naming

http://blog.csdn.net/zhu_liangwei/article/details/7667745

[3] What is the difference between the name of an underscore in a Python class?

http://www.zhihu.com/question/19754941

Explain the underline naming rules in Python

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.