对象名称前的单下划线和双下划线是什么意思? [英] What is the meaning of single and double underscore before an object name?

查看:257
本文介绍了对象名称前的单下划线和双下划线是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下在Python中对象名称前加下划线的确切含义,以及两者之间的区别吗?

Can someone please explain the exact meaning of having leading underscores before an object's name in Python, and the difference between both?

此外,无论所讨论的对象是变量,函数,方法还是其他,该含义是否保持不变?

Also, does that meaning stay the same whether the object in question is a variable, a function, a method, etc.?

推荐答案

单个下划线

在类中带有下划线的名称只是向其他程序员表明该属性或方法旨在私有.但是,名称本身并没有什么特别的事情.

Single Underscore

Names, in a class, with a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private. However, nothing special is done with the name itself.

引用 PEP-8 :

_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.

双下划线(名称修饰)

来自 Python文档:

任何形式为__spam的标识符(至少两个前导下划线,最多一个尾随下划线)在文本上均替换为_classname__spam,其中classname是当前类名,其中前导下划线被去除.进行这种修饰时无需考虑标识符的语法位置,因此可以用于定义类私有实例和类变量,方法,存储在全局变量中的变量,甚至是存储在实例中的变量.在其他类的实例上对此类私有.

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

以及同一页面上的警告:

And a warning from the same page:

名称重整旨在为类提供一种轻松的方法来定义私有"实例变量和方法,而不必担心派生类定义的实例变量或类外部代码使用实例变量进行处理的麻烦.请注意,整改规则主要是为了避免发生意外而设计的.坚定的灵魂仍然有可能访问或修改被视为私有的变量.

Name mangling is intended to give classes an easy way to define "private" instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private.

示例

>>> class MyClass():
...     def __init__(self):
...             self.__superprivate = "Hello"
...             self._semiprivate = ", world!"
...
>>> mc = MyClass()
>>> print mc.__superprivate
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: myClass instance has no attribute '__superprivate'
>>> print mc._semiprivate
, world!
>>> print mc.__dict__
{'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}

这篇关于对象名称前的单下划线和双下划线是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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