Python 中的 dunder 是什麽
版權聲明:博客為作者原創,允許轉載,但必須註明原文地址:https://www.cnblogs.com/byronxie/p/10741084.html
在 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
[3] Dunder (Double UNDERscore) Alias
Python 中的 dunder 是什麽