The following special forms using leading or trailing underscores are
recognized (these can generally be combined with any case convention):
_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.
single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).
__double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__,
__import__ or __file__. Never invent such names; only use them as documented.
其他受访者正确地将双前导和尾随下划线描述为“特殊”或“神奇”方法的命名约定。
虽然可以直接调用这些方法(例如,
[10, 20].__len__()
),但下划线的存在暗示着这些方法是有意间接调用的(例如,len([10, 20])
)。大多数python操作符都有一个关联的“magic”方法(例如,a[x]
是调用a.__getitem__(x)
的常用方法)。从Python PEP 8 -- Style Guide for Python Code:
请注意,带有双前导下划线和尾随下划线的名称本质上是为Python本身保留的:“永远不要发明这样的名称;只在文档中使用它们”。
被双下划线包围的名称对Python来说是“特殊的”。它们列在Python Language Reference, section 3, "Data model"中。
相关问题 更多 >
编程相关推荐