下划线 (_) 在 Python 中很非凡。

尽管下划线 (_) 在大多数语言中仅用于蛇形变量和函数(当然,不是全副),但它在 Python 中具备非凡含意。 如果你是 Python 程序员,对于 for _ in range(10)__init__(self) 之类的语法可能很相熟。

这篇文章将解释何时以及如何应用下划线 (_) 并帮忙你了解它。

在 Python 中应用下划线有5种状况。

  • 用于在解释器中存储最初一个表达式的值。
  • 用于疏忽特定值。 (所谓的“我不在乎”)
  • 为变量或函数的名称赋予非凡的含意和函数。
  • 用作“国际化(i18n)”或“本地化(l10n)”性能。
  • 分隔数字文字值。

让咱们看看每个案例。

在解释器中应用时

python 解释器将最初一个表达式值存储到名为“_”的非凡变量中。 此个性在规范 CPython 解释器中首先应用,你也能够在其余 Python 解释器中应用它。

>>> 10 10 >>> _ 10 >>> _ * 3 30 >>> _ * 20 600

疏忽值

下划线也用于疏忽特定值。 如果不须要特定值或未应用这些值,只需将值调配给下划线。

# Ignore a value when unpackingx, _, y = (1, 2, 3) # x = 1, y = 3 # Ignore the multiple values. It is called "Extended Unpacking" which is available in only Python 3.xx, *_, y = (1, 2, 3, 4, 5) # x = 1, y = 5 # Ignore the indexfor _ in range(10):         do_something()  # Ignore a value of specific locationfor _, val in list_of_tuple:    do_something()

给变量和函数的名称赋予非凡的含意

下划线可能最罕用于“命名”。 作为 Python 约定指南的 PEP8 介绍了以下 4 种命名状况。

单下划线前缀(_single)

该约定用于在模块中申明公有变量、函数、办法和类。 在 from module import * 中任何带有此约定的内容将被疏忽。

然而,当然,Python 并不反对真正的公有,所以咱们不能强制某些货色是公有的,也能够间接从其余模块调用它。 所以有时咱们说它是“弱外部应用示意”。

_internal_name = 'one_nodule' # private variable_internal_version = '1.0' # private variableclass _Base: # private class    _hidden_factor = 2 # private variable    def __init__(self, price):        self._price = price    def _double_price(self): # private method        return self._price * self._hidden_factor    def get_double_price(self):        return self._double_price() 

单下划线后缀(single_)

此约定可用于防止与 Python 关键字或内置函数发生冲突。 你可能不常常应用它。

Tkinter.Toplevel(master, class_='ClassName') # Avoid conflict with 'class' keywordlist_ = List.objects.get(1) # Avoid conflict with 'list' built-in type

双下划线前缀(__double)

这对于语法而不是约定。 双下划线将毁坏类的属性名称,以防止类之间的属性名抵触。 (所谓的“mangling”是指编译器或解释器用一些规定批改变量或函数名,而不是照原样应用)。

Python 的批改规定是在属性名称后面增加“_ClassName”,并用双下划线申明。

也就是说,如果你在一个类中编写名为“__method”的办法,该名称将被批改为“_ClassName__method”模式。

class A:    def _single_method(self):        pass    def __double_method(self): # for mangling        passclass B(A):    def __double_method(self): # for mangling        pass

因为双下划线命名的属性会像下面一样被毁坏,咱们不能用“ClassName.__method”来拜访它。 有时,有些人像真正公有那样应用这个性能,但它不是公有的,也不举荐应用。 无关更多详细信息,请浏览 Python 命名。

双下划线前后缀(__double__)

该约定用于非凡变量或办法(所谓的“魔术办法”),例如 __init____len__。 这些办法提供非凡的语法特色或做非凡的事件。 例如,__file__ 示意 Python 文件的地位,__eq__ 在执行a == b 表达式时执行。

用户当然能够自定义非凡办法,这种状况很少见,但往往可能会批改一些内置的非凡办法。 (例如,你应该应用 __init__ 初始化类,该类将在创立类的实例时首先执行。)

class A:    def __init__(self, a): # use special method '__init__' for initializing        self.a = a    def __custom__(self): # custom special method. you might almost do not use it        pass

作为国际化(i18n)/本地化(l10n)函数

它只是约定俗成,没有任何语法性能。 也就是说,下划线并不意味着 i18n/l10n,它只是一个约定,将 i18n/l10n 绑定到下划线变量。i18n/l10n的内置库 gettext 应用了这个约定,Python web 框架 Django 也反对 i18n/l10n, 引入并应用了这个约定。

# see official docs : https://docs.python.org/3/library/gettext.htmlimport gettextgettext.bindtextdomain('myapplication','/path/to/my/language/directory')gettext.textdomain('myapplication')_ = gettext.gettext# ...print(_('This is a translatable string.'))

分隔数字字面值

此个性是在 Python 3.6 中增加的。 它用于应用下划线分隔数字的字面值以进步可读性。

dec_base = 1_000_000bin_base = 0b_1111_0000hex_base = 0x_1234_abcdprint(dec_base) # 1000000print(bin_base) # 240print(hex_base) # 305441741

总结

到目前为止,咱们曾经介绍了 Python 的下划线。 尽管我是一名 Python 程序员,但在写这篇文章之前我并不理解其中的一些。 尤其是 i18n/l10n 对我来说很新。

像我一样,我心愿你从这篇文章中取得一些对于下划线的有用常识。

翻译
Understanding the underscore( _ ) of Python of Python")