何时在Python中使用一两个下划线 [英] When to use one or two underscore in Python

查看:139
本文介绍了何时在Python中使用一两个下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Ok I think I have understood the use of one and two heading underscores in Python.

如果我错了,请纠正我,

Correct me if I am wrong,

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

  1. In the case of one underscore, the underscore prevents the from X import * statement to import this kind of variables.

在两个下划线的情况下,变量的名称前面带有其所属的类的名称,以允许更高级别的私有性".

In the case of two underscores, the variable's name is prepended with the name of the class it belongs to allow a higher level of "privateness".

我现在的问题是:为什么不只使用两个下划线?在哪种情况下,(或需要)一个下划线比两个下划线更好?

My question now is: why not use two underscores only? In which cases one underscore is preferred (or needed) over two underscores?

推荐答案

简短的答案:除非您有真的令人信服的理由否则,请使用单个前导下划线(甚至三思而后行).

Short answer: use a single leading underscore unless you have a really compelling reason to do otherwise (and even then think twice).

长答案:

下划线表示这是实现细节"(属性,方法,函数等),在Java中与Python等效,称为保护".对于不属于类/模块/包公共API的名称,应使用此名称.仅是一种命名约定(大多数情况下-星号导入将忽略它们,但您不是在Python外壳程序之外的其他地方进行星号导入),因此它不会阻止任何人访问此名称,但随后它们会如果有任何问题,请自行承担责任(将其视为未密封的保修无效"之类的提法).

One underscore means "this is an implementation detail" (attribute, method, function, whatever), and is the Python equivalent of "protected" in Java. This is what you should use for names that are not part of your class / module / package public API. It's a naming convention only (well mostly - star imports will ignore them, but you're not doing star imports anywhere else than in your Python shell are you ?) so it won't prevent anyone to access this name, but then they're on their own if anything breaks (see this as a "warranty void if unsealed" kind of mention).

两个下划线会触发名称处理机制.很少有使用此功能的正当理由-实际上,我能想到的只有一个(并有文件证明):保护名称免遭在复杂框架内部的情况下意外覆盖.例如,在整个django代码库(主要在django.utils.functional软件包中)中,大约有六打或更少的这种命名方案实例.

Two underscores triggers a name mangling mechanism. There are very few valid reason to use this - actually there's only one I can think of (and which is documented): protecting a name from being accidentally overridden in the context of a complex framework's internals. As an example there might be about half a dozen or less instances of this naming scheme in the whole django codebase (mostly in the django.utils.functional package).

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

As far as I'm concerned I must have use this feature perhaps thrice in 15+ years, and even then I'm still not sure I really needed it.

这篇关于何时在Python中使用一两个下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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