关于命名约定:在Python中何时使用一个或两个下划线

When to use one or two underscore in Python

本问题已经有最佳答案,请猛点这里访问。

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

如果我错了就纠正我,

  • 在一个下划线的情况下,下划线会阻止from X import *语句导入此类变量。

  • 在两个下划线的情况下,变量的名称前面加上它所属的类的名称,以允许更高级别的"私有性"。

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


    简短的回答:使用一个前导下划线,除非你有一个真正令人信服的理由去做其他的事情(甚至可以三思而后行)。

    长回答:

    一个下划线的意思是"这是一个实现细节"(属性、方法、函数、任何东西),是爪哇中"保护"的Python等价物。这是不属于类/模块/包公共API的名称应该使用的名称。这只是一个命名约定(通常情况下,星导入会忽略它们,但除了在Python shell中,您没有在其他任何地方执行星导入吗?)所以这不会阻止任何人访问这个名字,但是如果有任何问题,他们会自己处理(把这看作是"未密封的保修无效"之类的说法)。

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

    就我而言,我必须在15年以上的时间里使用这项功能,也许是三次,即使如此,我仍然不确定我是否真的需要它。


    查看文档。

    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。双下划线:

    从python教程:

    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.