How to use the underline in Python _python

Source: Internet
Author: User
Tags in python

This article discusses how to use the Python underscore (_) character. We'll see that, as with many things in Python, the different uses of underscores (not all) are just common practice.


Single Underline (_)

Typically, it is used in the following 3 scenarios:

1, in the interpreter: in this case, "_" represents the result of the last executed statement in the interactive interpreter session. This usage is first adopted by the standard CPython interpreter, which is then followed by other types of interpreters.

>>> _ Traceback (most recent call last):
File "<stdin>", line 1, in <module>
nameerror:name ' _ ' is not defined
>>>
>>> _ '
>>> ' alright! ' if _ Else ':('
alright !'
>>> _
' alright! '

2, as a name: This is a little bit of contact with the above, at this time "_" as a temporary name use. This way, when someone else reads your code, you'll know that you've assigned a specific name, but you don't use that name again later. For example, in the following example, you may not be interested in the actual values in the loop count, and you can use "_" at this point.

n = A For
_ in range (n):
 do_something ()

3, Internationalization: Perhaps you have seen "_" will be used as a function. In this case, it is typically used to implement the function name of the translation lookup between internationalization and localized strings, which seems to derive from and follow the corresponding C conventions. For example, in the Django Document "Transformations" section, you will see the following code:

From django.utils.translation import Ugettext as _ from
django.http import HttpResponse
def my_view (Request): C4/>output = _ ("Welcome to My Site.")
 return HttpResponse (Output)

As you can see, the use of scenario two 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 Internationalized lookup conversion feature.


single underline before name (for example: _shahriar)

The programmer uses a single underline before the name to specify that the Name property is "private." This is a bit like practice, so that someone else (or yourself) can use the code to know that the name that starts with "_" is for internal use only. As described in the Python documentation:

Names that are prefixed with an underscore "_" (such as _spam) should be treated as a part of the API that is not exposed (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 you modify them.

As mentioned above, this is really similar to a convention, because it does have a certain meaning for the interpreter, and if you write the code "from < module/package name > Import *" Then the name beginning with "_" will not be imported unless the "__all__" in the module or package The list explicitly contains them. For more information, see "Importing * in Python".

Double underline before name (for example: __shahriar)

The use of the first double underline (__) of a name (specifically a method name) is not a convention, and it has a specific meaning for the interpreter. This usage in Python is intended to avoid a name conflict with a subclass definition. The Python document states that any identifier of the form "__spam" (at least two leading underscores, up to a subsequent underscore) will be replaced by the "_classname__spam" form, where "classname" is the current class name that removes the leading underscore. For example, the following example:

>>> class A (object):
... def _internal_use (self): ....
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". At this point, if you create a subclass B of a, you will not be able to easily overwrite the method "__method_name" in a.

>>> class B (A):
... def __method_name (self):
...
>>> dir (B ())
[' _a__method_name ', ' _b__method_name ', ..., ' _internal_use ']

The functionality here is almost the same as the final method in Java and the standard method in C + + classes (non-virtual methods).

Double underline before and after name (for example, __init__)

This usage represents a special method name in Python. In fact, this is just a convention, and for the Python system, this will ensure that no user-defined names 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 override the "__init__" method.

Although you can also write your own special method name, but do not do so.

>>> class C (object):
... def __mine__ (self):
...
>>> dir (C)
... [..., ' __mine__ ', ...]

In fact, it's easy to get rid of this type of naming and just let the special names defined within Python follow this convention.

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.