何时在 Python 中使用一个或两个下划线

When to use one or two underscore in Python

好的,我想我已经理解 Python 中一个和两个标题下划线的用法了。

如果我错了,请纠正我,

  1. 在一个下划线的情况下,下划线阻止from X import *语句导入这种变量。

  2. 在两个下划线的情况下,变量的名称前面加上它所属的class的名称允许更高级别的"privateness"。

我现在的问题是:为什么不只使用两个下划线呢?在哪些情况下,一个下划线优于(或需要)两个下划线?

查看文档。

1.单下划线

来自PEP-8

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

2。双下划线:

来自the Python tutorial

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

简短回答:使用一个前导下划线,除非您有 确实 令人信服的理由不这样做(即使那样也要三思)。

长答案:

一个下划线表示 "this is an implementation detail"(属性、方法、函数等),并且 Python 相当于 Java 中的 "protected"。对于不属于 class / 模块 / 包 public API 的名称,您应该使用这种名称。这只是一个命名约定(大多数情况下 - 明星进口会忽略它们,但你不会在你的 Python shell 以外的任何地方进行明星进口,你是吗?)所以它不会阻止任何人访问此名称,但如果出现任何问题,它们将自行解决(将其视为 "warranty void if unsealed" 类提及)。

两个下划线触发名称修改机制。使用这个的正当理由很少——实际上只有一个我能想到的(并且被记录在案):保护名称不被意外覆盖在复杂框架内部的上下文中.例如,在整个 django 代码库中(主要在 django.utils.functional 包中)可能有大约六个或更少的这种命名方案的实例。

就我而言,在 15 年多的时间里,我可能已经使用过此功能三次,但即便如此,我仍然不确定我是否真的需要它。