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?

相关文章
|
1月前
|
前端开发 Go Python
Python tricksUnderscores, Dunders, and More续篇
Python tricksUnderscores, Dunders, and More续篇
|
4月前
|
SQL 数据库 Python
【Python】已完美解决:(executemany()方法字符串参数问题)more placeholders in sql than params available
【Python】已完美解决:(executemany()方法字符串参数问题)more placeholders in sql than params available
73 1
|
4月前
|
Python
【Python】已解决:(Python xlwt写入Excel样式报错)ValueError: More than 4094 XFs (styles)
【Python】已解决:(Python xlwt写入Excel样式报错)ValueError: More than 4094 XFs (styles)
60 0
|
4天前
|
机器学习/深度学习 人工智能 TensorFlow
人工智能浪潮下的自我修养:从Python编程入门到深度学习实践
【10月更文挑战第39天】本文旨在为初学者提供一条清晰的道路,从Python基础语法的掌握到深度学习领域的探索。我们将通过简明扼要的语言和实际代码示例,引导读者逐步构建起对人工智能技术的理解和应用能力。文章不仅涵盖Python编程的基础,还将深入探讨深度学习的核心概念、工具和实战技巧,帮助读者在AI的浪潮中找到自己的位置。
|
4天前
|
机器学习/深度学习 数据挖掘 Python
Python编程入门——从零开始构建你的第一个程序
【10月更文挑战第39天】本文将带你走进Python的世界,通过简单易懂的语言和实际的代码示例,让你快速掌握Python的基础语法。无论你是编程新手还是想学习新语言的老手,这篇文章都能为你提供有价值的信息。我们将从变量、数据类型、控制结构等基本概念入手,逐步过渡到函数、模块等高级特性,最后通过一个综合示例来巩固所学知识。让我们一起开启Python编程之旅吧!
|
4天前
|
存储 Python
Python编程入门:打造你的第一个程序
【10月更文挑战第39天】在数字时代的浪潮中,掌握编程技能如同掌握了一门新时代的语言。本文将引导你步入Python编程的奇妙世界,从零基础出发,一步步构建你的第一个程序。我们将探索编程的基本概念,通过简单示例理解变量、数据类型和控制结构,最终实现一个简单的猜数字游戏。这不仅是一段代码的旅程,更是逻辑思维和问题解决能力的锻炼之旅。准备好了吗?让我们开始吧!
|
6天前
|
设计模式 算法 搜索推荐
Python编程中的设计模式:优雅解决复杂问题的钥匙####
本文将探讨Python编程中几种核心设计模式的应用实例与优势,不涉及具体代码示例,而是聚焦于每种模式背后的设计理念、适用场景及其如何促进代码的可维护性和扩展性。通过理解这些设计模式,开发者可以更加高效地构建软件系统,实现代码复用,提升项目质量。 ####
|
5天前
|
机器学习/深度学习 存储 算法
探索Python编程:从基础到高级应用
【10月更文挑战第38天】本文旨在引导读者从Python的基础知识出发,逐渐深入到高级编程概念。通过简明的语言和实际代码示例,我们将一起探索这门语言的魅力和潜力,理解它如何帮助解决现实问题,并启发我们思考编程在现代社会中的作用和意义。
|
5天前
|
机器学习/深度学习 数据挖掘 开发者
Python编程入门:理解基础语法与编写第一个程序
【10月更文挑战第37天】本文旨在为初学者提供Python编程的初步了解,通过简明的语言和直观的例子,引导读者掌握Python的基础语法,并完成一个简单的程序。我们将从变量、数据类型到控制结构,逐步展开讲解,确保即使是编程新手也能轻松跟上。文章末尾附有完整代码示例,供读者参考和实践。
|
6天前
|
人工智能 数据挖掘 程序员
Python编程入门:从零到英雄
【10月更文挑战第37天】本文将引导你走进Python编程的世界,无论你是初学者还是有一定基础的开发者,都能从中受益。我们将从最基础的语法开始讲解,逐步深入到更复杂的主题,如数据结构、面向对象编程和网络编程等。通过本文的学习,你将能够编写出自己的Python程序,实现各种功能。让我们一起踏上Python编程之旅吧!