Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

If you don't know the meaning of these five underscores, you can't really Python!

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

What is Python? Guido van Rossum, the father of Python, said: Python is a high-level programming language, and its core design philosophy is code readability and syntax, which allows programmers to express their ideas in very little code.

For me, the number one reason for learning Python is that Python is a language that can be programmed elegantly. It can write code and implement my ideas simply and naturally.

Another reason is that we can use Python in many ways: artificial intelligence, data science, Web development and machine learning can all be developed using Python.

During the National Day, a small friend left me a message and asked me: "what is the meaning of single underscore and double underscore in Python variable and method name?" I think some beginners or inexperienced friends will also have this question, so today I will talk to you about this very important "underlining" in Python!

Single underscore and double underscore have their own meanings in Python variables and method names. Some of the meanings are simply by convention and are seen as hints to programmers-while others are strictly enforced by the Python interpreter.

So, here's a look at the various meanings and naming conventions of single underscore and double underscore ("dunder") in Python, how name mangling works, and how it affects your own Python class.

The following five underscore modes and naming conventions are discussed, and how they affect the behavior of Python programs:

Single leading underscore: _ var

Single end underscore: var_

Double leading underscore: _ _ var

Double leading and trailing underscore: _ _ var__

Single underscore: _

1. Single leading underscore _ var

Programmers use a single underscore before the name to specify that the name attribute is private. This is a bit similar to convention, so that others (or yourself) will know that names that start with "_" are for internal use only. As described in the Python documentation:

Names prefixed with an underscore "_" (such as _ spam) should be treated as private parts of the API (whether they are functions, methods, or data members). At this point, they should be seen as implementation details, and no external notification is required when modifying them.

As mentioned above, this is indeed similar to a convention, because it does have some meaning for the interpreter, and if you write the code "from import *", names that start with "_" will not be imported unless they are explicitly included in the "_ _ all__" list in the module or package.

Look at the following example:

Class Test:

Def _ init__ (self):

Self.foo = 11

Self._bar = 23

What happens if you instantiate this class and try to access the foo and _ bar properties defined in the _ _ init__ constructor? Let's take a look:

> t = Test ()

> t.foo

eleven

> t._bar

twenty-three

You will see that a single underscore in _ bar does not prevent us from "entering" the class and accessing the value of the variable.

This is because a single underscore prefix in Python is just a convention-at least relative to variable and method names.

However, leading underscores do affect how names are imported from the module.

Suppose you have the following code in a module called my_module:

# This is my_module.py:

Def external_func ():

Return 23

Def _ internal_func ():

Return 42

Now, if you import all names from a module using wildcards, Python will not import names with leading underscores (unless the module defines a _ _ all__ list that overrides this behavior):

> from my_module import *

> > external_func ()

twenty-three

> _ internal_func ()

NameError: "name'_ internal_func' is not defined"

By the way, wildcard imports should be avoided because they make it unclear what names exist in the namespace. For the sake of clarity, it is better to stick to regular import.

Unlike wildcard imports, regular imports are not affected by leading individual underscore naming conventions:

> import my_module

> > my_module.external_func ()

twenty-three

> > my_module._internal_func ()

forty-two

It may be a little confusing for us to know this. If you follow PEP 8 recommendations to avoid wildcard imports, that's all you really need to remember:

A single underscore is an Python naming convention that indicates that the name is for internal use. It is usually not enforced by the Python interpreter, but only as a hint to the programmer.

2. Single end underlined var_

Sometimes, the most appropriate name of a variable is already occupied by a keyword. Therefore, names such as class or def cannot be used as variable names in Python. In this case, you can attach an underscore to resolve the naming conflict:

> def make_object (name, class):

SyntaxError: "invalid syntax"

> def make_object (name, class_):

... Pass

In summary, a single underscore (suffix) is a convention to avoid naming conflicts with the Python keyword. PEP 8 explains this convention.

3. Double leading underscore _ _ var

The use of a name (specifically a method name) preceded by a double underscore (_ _) is not a convention, but has a specific meaning for the interpreter. This usage in Python is used to avoid name conflicts with subclass definitions. The Python documentation indicates that any identifier in the form "_ _ spam" (at least two leading underscores and at most one subsequent underscore) will be replaced by the original text in the form "_ classname__spam", where "classname" is the current class name without the leading underscore.

For example, the following example:

> class A (object):

... Def _ internal_use (self):

... Pass

... Def _ method_name (self):

... Pass

...

> > dir (A ())

['_ averaged methodological names,...,'_ internal_use']

As expected, "_ internal_use" has not changed, while "_ _ method_name" has been changed to "_ ClassName__method_name". At this point, if you create a subclass B of A, you will not be able to easily override the method "_ _ method_name" in A.

> class B (A):

... Def _ method_name (self):

... Pass

...

> > dir (B ())

['_ averaged methodological names,'_ baked methodological names,...,'_ internal_use']

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

4. Double leading and double trailing underscore _ var_

Perhaps surprisingly, if a name begins and ends with a double underscore at the same time, the name modifier is not applied. Variables surrounded by double underscore prefixes and suffixes are not modified by the Python interpreter:

Class PrefixPostfixTest:

Def _ init__ (self):

Self.__bam__ = 42

> > PrefixPostfixTest (). _ _ bam__

forty-two

However, Python retains the name with double leading and double trailing underscore for special purposes. Examples of this are the _ _ init__ object constructor, or _ _ call__-which makes an object callable.

These dunder methods are often referred to as magic methods-but many people in the Python community don't like it.

It is best to avoid using names that begin and end with double underscores ("dunders") in your programs to avoid conflicts with future changes in the Python language.

5. Single underline _

Typically, it is used in the following three scenarios:

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

> _ Traceback (most recent call last):

File "", line 1, in

NameError: name'_'is not defined

> > 42

> _

forty-two

> 'alrightkeeper' If _ else': ('

'alrightship'

> _

'alrightship'

2. As a name: this is slightly related to the above point, where "_" is used as a temporary name. In this way, when others read your code, they will know that you have assigned a specific name, but will not use that name again later. For example, in the following example, you may not be interested in the actual value in the loop count, so you can use "_".

N = 42

For _ in range (n):

Do_something ()

3. Internationalization: you may have seen "_" used as a function. In this case, it is usually used to implement the function name of translation lookup between internationalized and localized strings, which seems to derive from and follow the corresponding C convention.

For example, in the "conversion" section of the Django document, you will 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 methods of use in scenarios 2 and 3 may conflict with each other, so we need to avoid using "_" as the temporary name in code blocks that use "_" as the internationalized lookup transformation function.

Summary:

Python underscore naming pattern-Summary

The following is a brief summary, the Quick Chart, which lists the meaning of the five Python underlining modes discussed in this article:

Welcome to join the 51 software testing family, where you will get [latest industry information], [free test tool installation package], [software testing technology], [job interview skills]. 51 learn and grow with you! Looking forward to your joining: QQ Group: 755431660

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report