python名字的来历_Python中dunder名称的来历

在 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 中的解释也加到词库中。

参考

本文的数字签名如下:

MGUCMGkxQcQNBCyoaOxWL0OJ0egTdwWs10aSObVMEW/+owscntk9/xXsmFThQNdZ28IePwIxAOrzdI3+A2WJdmxDOHuZDOpaLQBiPhfCkvSfuqC9ph/di23XR3hk0vqiYXQ5lSgWjg==

--- 2019-7-20 9:34:19

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值