欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python中dunder名称的来历

程序员文章站 2022-11-27 16:02:50
版权声明:博客为作者原创,允许转载,但必须注明原文地址:https://www.cnblogs.com/byronxie/p/10741084.html 在 Python 中,我们经常会看到被 双下划线 包围的属性名和方法名,比如下面代码中的 , , , 。初看还真奇怪啊,感觉别扭得很。 还有比长相 ......

版权声明:博客为作者原创,允许转载,但必须注明原文地址:

在 python 中,我们经常会看到被双下划线包围的属性名和方法名,比如下面代码中的 __future__, __all__, __version__, __author__。初看还真奇怪啊,感觉别扭得很。

"""this is the example module.

this module does stuff.
"""

from __future__ import barry_as_flufl

__all__ = ['a', 'b', 'c']
__version__ = '0.1'
__author__ = 'cardinal biggles'

import os
import sys

还有比长相更别扭的,就是怎么念它们。

这种风格的名字在 python 中有很多的名字,最开始叫魔法变量魔法函数 (magic)。

加两个下划线,这个名字就带有魔法了?

相信有很多人和我一样,把__all__念作magic all,就好像指着一匹马,我却要说牛一样。

所以后面有个人提议,把带双下划线的属性名和方法名叫dunders。大家都觉得很好,就慢慢流行起来了。在 python 的官方的 《 python 代码样式指南》(pep 8 -- style guide for python code [1]) 中,就把双下划线的名字叫做dunders

magic我还知道是魔法。我堂堂过了英语六级的人,看到dunders直接蒙圈了。有道词典一查,解释是 1). 甘蔗渣; 2). (dunder)人名.。 难道是一个叫 dunder 的人发明了双下划线命名法,为了纪念他,把带双下划线的名字都叫做 duner? 双下划线命名也有一个发明人?这太扯了。

后面有 bing 搜索(英文搜索, bing 比 baidu 好些, google 被墙用不了),终于在 python 官方的 wiki 中找到dunders的真正来历了 [3]。

原来 dunderdouble underscore(中文双下划线)的缩写,分别取doubledunderscoreunder组成。这样取名后方便发音。

在发明 dunder 之前, __init__ 要念作 double underscore init, 其中的double underscore 有17个单词,发音是6声(嘴或舌头要变换7次动作,你可以以试试),而dunder 只有6个单词,发音是2声。大大降低了手和嘴的劳动量,这个好的发明,当然举双手占成了。

python 官方 wiki 引用如下:

dunder (double underscore) alias

mark jackson was the first to suggest dunder as a speech shorthand for double underscores (__) in a reply to a query from pat notz. ned batchelder later stressed the need for a way of pronouncing __:

an awkward thing about programming in  python : there are lots of double underscores. [snip] my problem with the double underscore is that it's hard to say. how do you pronounce __init__? "underscore underscore init underscore underscore"? "under under init under under"? just plain "init" seems to leave out something important. i have a solution: double underscore should be pronounced "dunder". so __init__ is "dunder init dunder", or just "dunder init".

顺便给有道词典提了个建议,把dunder在 python 中的解释也加到词库中。

参考

[1] module level dunder names

[2] using and abusing python 's double-underscore methods and attributes

[3] dunder (double underscore) alias