在 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].
原来 dunder 是 Double Underscore(中文双下划线) 的缩写, 分别取 Double 的 D 和 Underscore 的 Under 组成. 这样取名后方便发音.
在发明 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 https://github.com/vakila/dunders
[3] Dunder (Double Underscore) Alias https://wiki.python.org/moin/DunderAlias
来源: https://www.cnblogs.com/byronxie/p/10741084.html