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?

相关文章
|
11月前
|
前端开发 Go Python
Python tricksUnderscores, Dunders, and More续篇
Python tricksUnderscores, Dunders, and More续篇
52 0
|
SQL 数据库 Python
【Python】已完美解决:(executemany()方法字符串参数问题)more placeholders in sql than params available
【Python】已完美解决:(executemany()方法字符串参数问题)more placeholders in sql than params available
209 1
|
Python
【Python】已解决:(Python xlwt写入Excel样式报错)ValueError: More than 4094 XFs (styles)
【Python】已解决:(Python xlwt写入Excel样式报错)ValueError: More than 4094 XFs (styles)
146 0
|
6月前
|
机器学习/深度学习 存储 设计模式
Python 高级编程与实战:深入理解性能优化与调试技巧
本文深入探讨了Python的性能优化与调试技巧,涵盖profiling、caching、Cython等优化工具,以及pdb、logging、assert等调试方法。通过实战项目,如优化斐波那契数列计算和调试Web应用,帮助读者掌握这些技术,提升编程效率。附有进一步学习资源,助力读者深入学习。
|
3月前
|
Python
Python编程基石:整型、浮点、字符串与布尔值完全解读
本文介绍了Python中的四种基本数据类型:整型(int)、浮点型(float)、字符串(str)和布尔型(bool)。整型表示无大小限制的整数,支持各类运算;浮点型遵循IEEE 754标准,需注意精度问题;字符串是不可变序列,支持多种操作与方法;布尔型仅有True和False两个值,可与其他类型转换。掌握这些类型及其转换规则是Python编程的基础。
205 33
|
2月前
|
数据采集 分布式计算 大数据
不会Python,还敢说搞大数据?一文带你入门大数据编程的“硬核”真相
不会Python,还敢说搞大数据?一文带你入门大数据编程的“硬核”真相
76 1
|
3月前
|
设计模式 安全 Python
Python编程精进:正则表达式
正则表达式是一种强大的文本处理工具,用于搜索、匹配和提取模式。本文介绍了正则表达式的语法基础,如`\d`、`\w`等符号,并通过实例展示其在匹配电子邮件、验证电话号码、处理日期格式等场景中的应用。同时,文章提醒用户注意性能、编码、安全性等问题,避免常见错误,如特殊字符转义不当、量词使用错误等。掌握正则表达式能显著提升文本处理效率,但需结合实际需求谨慎设计模式。
134 2
|
4月前
|
数据采集 安全 BI
用Python编程基础提升工作效率
一、文件处理整明白了,少加两小时班 (敲暖气管子)领导让整理100个Excel表?手都干抽筋儿了?Python就跟铲雪车似的,哗哗给你整利索!
113 11
|
6月前
|
人工智能 Java 数据安全/隐私保护
[oeasy]python081_ai编程最佳实践_ai辅助编程_提出要求_解决问题
本文介绍了如何利用AI辅助编程解决实际问题,以猫屎咖啡的购买为例,逐步实现将购买斤数换算成人民币金额的功能。文章强调了与AI协作时的三个要点:1) 去除无关信息,聚焦目标;2) 将复杂任务拆解为小步骤,逐步完成;3) 巩固已有成果后再推进。最终代码实现了输入验证、单位转换和价格计算,并保留两位小数。总结指出,在AI时代,人类负责明确目标、拆分任务和确认结果,AI则负责生成代码、解释含义和提供优化建议,编程不会被取代,而是会更广泛地融入各领域。
183 28
|
6月前
|
机器学习/深度学习 数据可视化 TensorFlow
Python 高级编程与实战:深入理解数据科学与机器学习
本文深入探讨了Python在数据科学与机器学习中的应用,介绍了pandas、numpy、matplotlib等数据科学工具,以及scikit-learn、tensorflow、keras等机器学习库。通过实战项目,如数据可视化和鸢尾花数据集分类,帮助读者掌握这些技术。最后提供了进一步学习资源,助力提升Python编程技能。

热门文章

最新文章

推荐镜像

更多