在 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 中的解釋也加到詞庫中。
參考
[2] Using and abusing Python 's double-underscore methods and attributes
[3] Dunder (Double UNDERscore) Alias
版權聲明:本文為作者原創,允許轉載,但必須注明原文地址:https://www.cnblogs.com/byronsh/p/10741084.html
本文的數字簽名如下:
MGUCMGkxQcQNBCyoaOxWL0OJ0egTdwWs10aSObVMEW/+owscntk9/xXsmFThQNdZ28IePwIxAOrzdI3+A2WJdmxDOHuZDOpaLQBiPhfCkvSfuqC9ph/di23XR3hk0vqiYXQ5lSgWjg==
--- 2019-7-20 9:34:19