为什么某些函数具有下划线“__”函数名称前后? [英] Why do some functions have underscores "__" before and after the function name?
问题描述
另外,是否有人并解释哪些函数倾向于有下划线,以及为什么(例如 __ init __
)?
从 Python PEP 8 - Python代码样式指南:
以下使用开头或结尾下划线的特殊格式是
识别(这些通常可以与任何案件惯例结合):
_single_leading_underscore
:弱的内部使用指标。例如。来自M import *
不会导入名称以下划线开头的对象。
- 当命名一个类属性时,调用名字改变(在类FooBar中,
single_trailing_underscore _
:常规使用,以避免与Python关键字冲突,例如
Tkinter.Toplevel(master,class_ ='ClassName')
__ boo
变为_FooBar__boo
;见下文)。
__ double_leading_and_trailing_underscore __
:生活在用户控制的命名空间中的魔术对象或属性。例如。__ init __
,
__ import __
或__ file __
。不要发明这样的名字;请注意,带有双引号和尾部下划线的名称基本上是为Python本身保留的:永远不要发明这样的名字,只能按照文档的方式使用它们。This seems to occur a lot, and was wondering if this was a requirement in the Python language, or merely a matter of convention?
Also, could someone name and explain which functions tend to have the underscores, and why (
__init__
, for instance)?解决方案From the 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.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屋!