The Magic underline in Python

Source: Internet
Author: User
Tags i18n

A single underscore (_) is typically used in three ways:
    1. In the Python interpreter: A single underscore represents the result of the last execution in the interactive Interpretation session (console). This was first implemented in the standard CPython interpreter, which is then preserved:
>>>_ Traceback (most recent): File"<stdin>", line1,inch<module>Nameerror:name'_'  isNot defined>>> the>>> _   the>>>'alright!' if_Else ':('  'alright!'>>> _  'alright!'

2. As a name: this may be somewhat relevant to the point. A single underline is used as the name ' discarded '. This may be the next person to read your code to know that, by convention, underscores represent variables that are declared but not used. As you will not be interested in variables that count loops:

 the   for inch range (N):      do_something ()

3.I18N: There are times when a single underscore is declared as a function. In this case, this function is usually used for internationalization as well as localized character conversions and lookups. This habit seems to be the source and will continue to follow the corresponding C-language habits. As an example, as in Django documentation for translation, you can see:

 from  as  _    from django.http Import HttpResponse    def my_view (request):      = _ ("Welcome to my site. " )      return httpresponse (output)

There is a conflict between the second and the 32 usages, so you should avoid using underscores as ' discarded ' variables and i18n to find and transform .

Add a single underscore to the name (for example, _name)

Add a single underscore to the name so that it can be used to tell the programmer that the variable is a private variable. This is a convention that allows the next person (or yourself) to use the code, knowing that the underscore variable is only used for internal invocation. As the Python document records:

As a non- Public is a function, a method or a data member).  It should is considered an implementation detail and subject to the change without notice.

I explain this practice because, in the interpreter, it represents some specific usage. If you are from <module/package> import *, unless the module ' s/package ' s __all__ file explicitly lists those variables with a single underscore prefix, Otherwise, none of these variables will be imported. See "Importing ' * ' from Python" For more information

Add two underscores (for example, __name) before the name

adding two underscores (especially the name of a function) before the name is not a convention. This is a special meaning for the interpreter. python will mangles (attribute nouns, do not translate, or can say let ....) Missing meaning) These variables, thus avoiding the subclass definition of the variable and the base class conflict. As the Python document says, any variable __spam in this form (at least two prefix underscores, up to one suffix underscore) will be replaced with _classname__spam, and the underscore of the prefix in the current class classname is truncated.

You can look at the following example:

class A (object):  ...     def _internal_use (self):  ...         Pass  ...     def __method_name (self):  ...         Pass  ...    >>> dir (A ())  ['_a__method_name'_ Internal_use']

As is said, _internal_use has not changed and __method_name is mangled to _classname__method_name. Now, if you want to declare a subclass of a, B, and then you want to rewrite A's __method_ Name is not that easy either:

class B (A):  ...     def __method_name (self):  ...         Pass  ...    >>> dir (B ())  ['_a__method_name'_b__ Method_name'_internal_use']

This default attribute is equivalent to the final method of Java and the common method of C + + (non-virtual function)


The name is preceded by two underscores (for example, __init__)

In Python this represents this particular method. Personally, this is just a convention that allows Python systems to use variables in a way that does not conflict with user-defined variables. When Python calls them, you can typically override these methods and then define the behavior of the settings. For example, when declaring a class, you often overwrite the __init__ method.

No one prevents you from writing your own variable that looks like a special method (but, Best of all):

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

It's easy to get away from this type of variable declaration, as long as you let Python custom special variables declare yourself to follow this convention.



The Magic underline 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.