Underline in python skills (1) and underline in python skills

Source: Internet
Author: User

Underline in python skills (1) and underline in python skills
1. Functions of _ all _ in the moudles file of python

Moudle in Python is a very important concept. I have seen a _ init _. py file in moudle written by many people. Some _ init _. py are blank, while others have the _ all _ parameter. The following table lists the functions of the _ all _ parameter.

If _ init _. py is blank during other page import *, you can directly import all functions in moudle. If _ init _. py defines _ all __, only part of the content defined by _ all _ will be imported during import.

Example: __all _ = ['user', 'usercode', 'Tweet ',]

 

2. _ slots _ is used to limit class attributes, for example:

Class A (object ):
_ Slots _ = ['var']

In this case, when an external call is performed, such:
A = ()
A. var = 4 # No error is reported
A. other = 4 # at this time, an AttributeError will be thrown.

 

3. The following tips can be used to obtain private variables:

Python does not have real private variables. The internal implementation is to convert the private variable process. The rule is: _ <Class Name> <private variable>

1 class Test(object):2     def __init__(self):3         self.__zzz=1114 5 if __name__ == '__main__':6     a =  Test()7     print a._Test__zzz

Similarly, you can use a. _ Test _ zzz = 222 to modify the value of a private variable.

 

4. Underline type

Single underline ( _)

There are three main cases:

1. In the interpreter

_A symbol is the result returned by the last statement executed in the interactive interpreter. This method was initially used in the CPython interpreter, and other interpreters were followed up later.

>>> _Traceback (most recent call last):  File "", line 1, in NameError: name '_' is not defined>>> 42>>> _42>>> 'alright!' if _ else ':(''alright!'>>> _'alright!'
2. Use as the name

This is a bit similar to above._UsedDiscarded. By convention, this will let people who read your code know that this is a specific name that will not be used. For example, you may not have a cyclic Count value:

n = 42for _ in range(n):    do_something()
3. i18n

_It can also be used as a function name. In this case, a single underline is often used as the function name for international and localized string translation queries. This Convention seems to have originated from the C language. For example, in Django documentation for translation, you may see:

from django.utils.translation import ugettext as _from django.http import HttpResponsedef my_view(request):    output = _("Welcome to my site.")    return HttpResponse(output)

The second and third methods may cause conflicts, so if you use_Use i18n translation query functions insteadDiscardedVariable name.

Name with a single underline prefix (for example _shahriar)

The name prefixed with a single underline specifies that the name is "private ". InSomeIn the import * scenario, the next person using your code (or yourself) will understand that this name is only used internally. Python documentation writes:

a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

InSomeThe import * scenario is because the interpreter does process the name starting with a single underline during import. If you writefrom <module/package> import *, Any name starting with a single underline will not be imported, unless the module/package's__all__The list explicitly contains these names. For more information, see "Importing * in Python ".

Name of the double-underline prefix (for example __shahriar)

A name prefix (especially a method name) with double underscores is not a convention; it has a specific meaning for the interpreter. Python will rewrite these names to avoid conflicts with the names defined in the subclass. As mentioned in Python documentation__spamThis form (starting with at least two underscores,Most of them end with an underscore.._classname__spam, WhereclassnameIs the current class name, with an underscore prefix.
Let's look at the example below:

>>> class A(object):...     def _internal_use(self):...         pass...     def __method_name(self):...         pass... >>> dir(A())['_A__method_name', ..., '_internal_use']

As expected,_internal_useNot changed,__method_nameChanged_ClassName__method_name. CreateASubclassB(This is not a good name ).AIn__method_nameNow:

>>> class B(A):...     def __method_name(self):...         pass... >>> dir(B())['_A__method_name', '_B__method_name', ..., '_internal_use']

This specific behavior is almost equivalentfinalMethod and normal method in C ++ (non-virtual method ).

Names with double underscores (such __init__)

These are special method names of Python. This is just a convention. It is a way to ensure that names in the Python system do not conflict with custom names. You can override these methods to generate the desired behavior when Python calls them. For example, when writing a class__init__Method.
You can also write your own "special method" Name (but do not do this ):

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

Do not write the method name like this. Use this Convention only for the special method names defined by Python.

 

5. Are these naming differences?

1. Names starting with an underscore, such as _ getFile
2. names starting with two underscores (_ filename)
3. names starting with and ending with two underscores, such as _ init __()
4. Others

The first step is to start with a single underline. This is often used in modules. Variables and functions starting with a single underline in a module are considered as internal functions by default. If you use from a_module import * for import, these variables and functions are not imported. However, if you use import a_module to import a module, you can still access such an object in the format of a_module. _ some_var.

There is also a style ending with a single underline in the Code style officially recommended by Python, which does not have a special meaning during parsing, but is usually used to distinguish it from the Python keywords, for example, if we need a variable named class, but the class is a keyword of Python, we can end with a single underline to write class _.

Name Mangling (Name Mangling) is used in the class members of Python. If there is a member named _ x in the Test class, dir (Test) _ Test _ x instead of _ x. This is to avoid conflicts between the member name and the name in the subclass. Note that this requires that the name is not followed by an underscore.

The Double underline begins with the double underline and ends with some Python "magic" objects, such as _ init _, _ del _, _ add _, and _ getitem _ of class members, and global _ file _ and _ name. The official recommendation of Python never applies this naming method to its own variables or functions, but uses it according to the instructions in the document.

In addition, an extension library written in C is often named after an underscore and packaged with a Python module that removes the underline. For example, struct is actually a Python package of C Module _ struct.

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.