为什么有些函数有下划线“__"?在函数名之前和之后? [英] Why do some functions have underscores "__" before and after the function name?

查看:34
本文介绍了为什么有些函数有下划线“__"?在函数名之前和之后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这种下划线"似乎经常出现,我想知道这是 Python 语言中的要求,还是仅仅是约定问题?

This "underscoring" seems to occur a lot, and I was wondering if this was a requirement in the Python language, or merely a matter of convention?

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

Also, could someone name and explain which functions tend to have the underscores, and why (__init__, for instance)?

推荐答案

来自 PythonPEP 8 -- Python 代码风格指南:

以下使用前导或尾随下划线的特殊形式是公认的(这些通常可以与任何大小写约定结合使用):

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:弱内部使用"指标.例如.from M import * 不导入名称以下划线开头的对象.

  • _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_:按照惯例使用以避免与 Python 关键字冲突,例如

single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

Tkinter.Toplevel(master, class_='ClassName')

__double_leading_underscore:在命名类属性时,调用名称修改(在类 FooBar 中,__boo 变为 _FooBar__boo;见下文).

__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__:存在于用户控制的命名空间中的神奇"对象或属性.例如.__init__,__import____file__.永远不要发明这样的名字;仅按照文档使用它们.

__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 本身保留的:切勿发明此类名称;仅将它们用作文档".

Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".

这篇关于为什么有些函数有下划线“__"?在函数名之前和之后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆