Python tricksUnderscores, Dunders, and More

简介: Python tricksUnderscores, Dunders, and More

Python tricks:Underscores, Dunders, and More
Single and double underscores have a meaning in Python variable and method names. Some of that meaning is merely by convention and intended as a hint to the programmer–and someof it is enforced by the Python interpreter.

If you’re wondering, “What’s the meaning of single and double underscores in Python variable and method names?” I’ll do my best to get you the answer here. Now, we’ll discuss the following five underscore patterns and naming conventions, and how they affect the behavior of your Python programs:

Single Leading Underscore: var
Single Trailing Underscore: var

Double Leading Underscore:var
Double ledaing and Trailing Underscore:
var_
Single Underscore:

1. Single Leading Underscore:“_var”
When it comes to variable and method names, the single underscore prefix has a meaning by convention only.It’s a hint to the programmer–it means what the Python community agrees it should mean, but it does not affect the behavior of your programs.

The underscore prefix is meant as a hint to tell another programmer that a variable or method starting with a single underscore is intended for internal use. This convention is defined in PEP 8, the most commonly used Python code style guide.

However, this convention isn’t enforced by the Python interpreter. Python does not have strong distinctions between “private” and “public” variable like Java does. Adding a single underscore in front of a variable name is more like someone putting up a tiny underscore warning sign that says:" Hey, this isn’t really meant to be a part of the public interface of this class. Best to leave it alone."

Take a look at the following example:

class Test:
  def __init__(self):
    self.foo = 11
    self._bar = 23

What’s going to happen if you instantiate this class and try to access the foo and _bar attributes defined in its initconstructor?

Let’s find out:

>>> t = Test()
>>> t.foo
11
>>> t._bar
23

As you can see, the leading single underscore in _bar did not prevent us from “reaching into” the class and accessing the value of that variable.

That’s because the single underscore prefix in Python is merely an agreed-upon convention–at least when it comes to variable and method names.

However, leading underscore do impact how names get imported from modules. Imagine you had the following code in a module called my_module:

# my_moudle.py
def external_func():
    return 23

def _internal_func():
    return 42

Now, if you use a wildcard import to import all the names from the module, Python will not import names with a leading underscore(unless the module defines an alllist that overrides this behavior):

from my_module import *
external_func()
_internal_func()

  File "/Users/liuxiaowei/PycharmProjects/Python_trick/ll.py", line 3, in <module>
    _internal_func()
NameError: name '_internal_func' is not defined

By the way, wildcard imports should be voided as they make it unclear which names are present in the namespace. It’s better to stick to regular imports for the sake of clarity. Unlike wildcard imports, regular imports are not affected by the leading single underscore naming convention:

import my_module
print(my_module.external_func())
print(my_module._internal_func())

/Users/liuxiaowei/PycharmProjects/venv/bin/python /Users/liuxiaowei/PycharmProjects/Python_trick/ll.py
23
42

I know this might be a little confusing at this point. If you stick to the PEP 8 recommendation that wildcard imports should be avoided, then all you really need to remember is this:

Single undersocres are a Python naming convention that indicates a name is meant for internal use. It is generally not enforced by the Python interpreter and is only meant as a hint to the programmer.

2. Single Trailing Underscore:“var_”
Sometimes the most fitting name for a variable is already taken by a keyword in the Python language. Therefore, names like class or def cannot be used as variable names in Python. In this case, you can append a single underscore to break the naming conflict:

>>> def make_object(name, class):
  SyntaxError: invalid syntax

>>> def make_object(name, class_):
...     pass

In summary, a single trailing underscore(postfix) is used by convention to avoid naming conflicts with Python keywords. This convention is defined and explained in PEP 8.

To be continued…

接下文 Python tricksUnderscores, Dunders, and More续篇https://developer.aliyun.com/article/1618439?

相关文章
|
前端开发 Go Python
Python tricksUnderscores, Dunders, and More续篇
Python tricksUnderscores, Dunders, and More续篇
218 0
|
SQL 数据库 Python
【Python】已完美解决:(executemany()方法字符串参数问题)more placeholders in sql than params available
【Python】已完美解决:(executemany()方法字符串参数问题)more placeholders in sql than params available
471 1
|
Python
【Python】已解决:(Python xlwt写入Excel样式报错)ValueError: More than 4094 XFs (styles)
【Python】已解决:(Python xlwt写入Excel样式报错)ValueError: More than 4094 XFs (styles)
315 0
|
10月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
1656 102
|
10月前
|
数据采集 机器学习/深度学习 算法框架/工具
Python:现代编程的瑞士军刀
Python:现代编程的瑞士军刀
504 104
|
10月前
|
人工智能 自然语言处理 算法框架/工具
Python:现代编程的首选语言
Python:现代编程的首选语言
397 103
|
10月前
|
机器学习/深度学习 人工智能 数据挖掘
Python:现代编程的首选语言
Python:现代编程的首选语言
427 82
|
9月前
|
Python
Python编程:运算符详解
本文全面详解Python各类运算符,涵盖算术、比较、逻辑、赋值、位、身份、成员运算符及优先级规则,结合实例代码与运行结果,助你深入掌握Python运算符的使用方法与应用场景。
526 3
|
9月前
|
数据处理 Python
Python编程:类型转换与输入输出
本教程介绍Python中输入输出与类型转换的基础知识,涵盖input()和print()的使用,int()、float()等类型转换方法,并通过综合示例演示数据处理、错误处理及格式化输出,助你掌握核心编程技能。
760 3
|
9月前
|
并行计算 安全 计算机视觉
Python多进程编程:用multiprocessing突破GIL限制
Python中GIL限制多线程性能,尤其在CPU密集型任务中。`multiprocessing`模块通过创建独立进程,绕过GIL,实现真正的并行计算。它支持进程池、队列、管道、共享内存和同步机制,适用于科学计算、图像处理等场景。相比多线程,多进程更适合利用多核优势,虽有较高内存开销,但能显著提升性能。合理使用进程池与通信机制,可最大化效率。
579 3

推荐镜像

更多