• 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]。

    原来 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

    版权声明:本文为作者原创,允许转载,但必须注明原文地址:https://www.cnblogs.com/byronsh/p/10741084.html


    本文的数字签名如下:

    MGUCMGkxQcQNBCyoaOxWL0OJ0egTdwWs10aSObVMEW/+owscntk9/xXsmFThQNdZ28IePwIxAOrzdI3+A2WJdmxDOHuZDOpaLQBiPhfCkvSfuqC9ph/di23XR3hk0vqiYXQ5lSgWjg==
    --- 2019-7-20 9:34:19

    数字签名验证方法

  • 相关阅读:
    break和continue
    while循环嵌套
    while循环语句
    SDUT 2766-小明传奇2(母函数)
    那些奇妙的"大师"是怎样炼成的(科学、迷信、心理)
    深入理解Linux字符设备驱动
    [从头学数学] 第162节 锐角三角函数
    iOS将数组中的内容分拼接成字符串
    win10 UWP 全屏
    杂(三)-The type java.lang.Object cannot be resolved It is indirectly referenced ...
  • 原文地址:https://www.cnblogs.com/byronsh/p/10741084.html
Copyright © 2020-2023  润新知