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?

相关文章
|
2月前
|
前端开发 Go Python
Python tricksUnderscores, Dunders, and More续篇
Python tricksUnderscores, Dunders, and More续篇
25 0
|
5月前
|
SQL 数据库 Python
【Python】已完美解决:(executemany()方法字符串参数问题)more placeholders in sql than params available
【Python】已完美解决:(executemany()方法字符串参数问题)more placeholders in sql than params available
97 1
|
5月前
|
Python
【Python】已解决:(Python xlwt写入Excel样式报错)ValueError: More than 4094 XFs (styles)
【Python】已解决:(Python xlwt写入Excel样式报错)ValueError: More than 4094 XFs (styles)
72 0
|
17天前
|
人工智能 数据可视化 数据挖掘
探索Python编程:从基础到高级
在这篇文章中,我们将一起深入探索Python编程的世界。无论你是初学者还是有经验的程序员,都可以从中获得新的知识和技能。我们将从Python的基础语法开始,然后逐步过渡到更复杂的主题,如面向对象编程、异常处理和模块使用。最后,我们将通过一些实际的代码示例,来展示如何应用这些知识解决实际问题。让我们一起开启Python编程的旅程吧!
|
16天前
|
存储 数据采集 人工智能
Python编程入门:从零基础到实战应用
本文是一篇面向初学者的Python编程教程,旨在帮助读者从零开始学习Python编程语言。文章首先介绍了Python的基本概念和特点,然后通过一个简单的例子展示了如何编写Python代码。接下来,文章详细介绍了Python的数据类型、变量、运算符、控制结构、函数等基本语法知识。最后,文章通过一个实战项目——制作一个简单的计算器程序,帮助读者巩固所学知识并提高编程技能。
|
4天前
|
Unix Linux 程序员
[oeasy]python053_学编程为什么从hello_world_开始
视频介绍了“Hello World”程序的由来及其在编程中的重要性。从贝尔实验室诞生的Unix系统和C语言说起,讲述了“Hello World”作为经典示例的起源和流传过程。文章还探讨了C语言对其他编程语言的影响,以及它在系统编程中的地位。最后总结了“Hello World”、print、小括号和双引号等编程概念的来源。
98 80
|
22天前
|
存储 索引 Python
Python编程数据结构的深入理解
深入理解 Python 中的数据结构是提高编程能力的重要途径。通过合理选择和使用数据结构,可以提高程序的效率和质量
134 59
|
2天前
|
分布式计算 大数据 数据处理
技术评测:MaxCompute MaxFrame——阿里云自研分布式计算框架的Python编程接口
随着大数据和人工智能技术的发展,数据处理的需求日益增长。阿里云推出的MaxCompute MaxFrame(简称“MaxFrame”)是一个专为Python开发者设计的分布式计算框架,它不仅支持Python编程接口,还能直接利用MaxCompute的云原生大数据计算资源和服务。本文将通过一系列最佳实践测评,探讨MaxFrame在分布式Pandas处理以及大语言模型数据处理场景中的表现,并分析其在实际工作中的应用潜力。
16 2
|
16天前
|
小程序 开发者 Python
探索Python编程:从基础到实战
本文将引导你走进Python编程的世界,从基础语法开始,逐步深入到实战项目。我们将一起探讨如何在编程中发挥创意,解决问题,并分享一些实用的技巧和心得。无论你是编程新手还是有一定经验的开发者,这篇文章都将为你提供有价值的参考。让我们一起开启Python编程的探索之旅吧!
41 10
|
19天前
|
机器学习/深度学习 人工智能 Java
Python 语言:强大、灵活与高效的编程之选
本文全面介绍了 Python 编程语言,涵盖其历史、特点、应用领域及核心概念。从 1989 年由 Guido van Rossum 创立至今,Python 凭借简洁的语法和强大的功能,成为数据科学、AI、Web 开发等领域的首选语言。文章还详细探讨了 Python 的语法基础、数据结构、面向对象编程等内容,旨在帮助读者深入了解并有效利用 Python 进行编程。
下一篇
DataWorks