为什么有些函数的函数名前后都有双下划线“__”?

2024-04-26 20:28:53 发布

您现在位置:Python中文网/ 问答频道 /正文

这似乎经常发生,并且想知道这是Python语言中的一个需求,还是仅仅是一个约定的问题?

另外,有人能说出并解释哪些函数倾向于使用下划线,以及为什么(__init__,例如)?


Tags: 函数语言init
3条回答

其他受访者正确地将双前导和尾随下划线描述为“特殊”或“神奇”方法的命名约定。

虽然可以直接调用这些方法(例如,[10, 20].__len__()),但下划线的存在暗示着这些方法是有意间接调用的(例如,len([10, 20]))。大多数python操作符都有一个关联的“magic”方法(例如,a[x]是调用a.__getitem__(x)的常用方法)。

Python PEP 8 -- Style Guide for Python Code

Descriptive: Naming Styles

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.

请注意,带有双前导下划线和尾随下划线的名称本质上是为Python本身保留的:“永远不要发明这样的名称;只在文档中使用它们”。

被双下划线包围的名称对Python来说是“特殊的”。它们列在Python Language Reference, section 3, "Data model"中。

相关问题 更多 >