Python 中的私有成员
如何在 Python 中将方法和数据成员设为私有?或者Python不支持私有成员?
How can I make methods and data members private in Python? Or doesn't Python support private members?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
因此,例如
将输出:
__private_symbol
应该被考虑一个私有方法,但仍然可以通过_Test__private_symbol
访问它。So, for example,
will output:
__private_symbol
should be considered a private method, but it would still be accessible through_Test__private_symbol
.其他答案提供了技术细节。一方面,我想强调 Python 与 C++/Java 等语言(根据您的问题,我认为您很熟悉)之间的哲学差异。
Python(以及 Perl)的普遍态度是,属性的“隐私”是对程序员的请求,而不是编译器/解释器的铁丝网。这个想法在此邮件中得到了很好的总结,并且经常被引用“我们都是同意的成年人”,因为它“假设”程序员有足够的责任不干涉内部。前导下划线用作礼貌消息,表明该属性是内部属性。
另一方面,如果您确实想要访问某些应用程序的内部结构(一个值得注意的例子是像 pydoc 这样的文档生成器),您可以随意这样做。作为一名程序员,你有责任知道自己在做什么并正确地完成它,而不是语言强迫你按它的方式做事。
The other answers provide the technical details. I'd like to emphasise the difference in philosophy between Python on one hand and languages like C++/Java (which I presume you're familiar with based on your question).
The general attitude in Python (and Perl for that matter) is that the 'privacy' of an attribute is a request to the programmer rather than a barbed wire fence by the compiler/interpreter. The idea is summarised well in this mail and is often referred to as "We're all consenting adults" since it 'assumes' that the programmer is responsible enough to not meddle with the insides. The leading underscores serve as a polite message saying that the attribute is internal.
On the other hand, if you do want to access the internals for some applications (a notable example is documentation generators like pydoc), you're free to do so. Onus is on you as a programmer to know what you're doing and do it properly rather than on the language to force you do to things it's way.
Python 中没有任何其他访问保护机制的
private
。 Python 风格指南 中记录了一个约定,用于向用户指示你的班级他们不应该访问某些属性。_single_leading_underscore:弱“内部使用”指示符。例如
from M import *
不会导入名称以下划线开头的对象。single_trailing_underscore_:按约定使用以避免与Python关键字冲突,例如
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore:命名类属性时,调用名称修饰(在类 FooBar 中,__boo 变为 _FooBar__boo;见下文)。
There are no
private
of any other access protection mechanisms in Python. There is a convention documented in the Python style guide for indicating to the users of your your class that they should not be accessing certain attribute._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).
深入了解 Python
Dive Into Python
Python 不直接支持隐私。程序员需要知道何时可以安全地从外部修改属性,但无论如何使用 python,你可以通过一些小技巧实现诸如 private 之类的东西。
现在让我们看看一个人是否可以将任何内容设为私有。
现在当我们执行时:
那么某人如何访问该变量???
你可以这样做:
哇,实际上,如果 python 获取任何以双下划线开头的变量,则通过在开头添加一个下划线和类名来“翻译”:
注意:如果你不想要这样名称更改,但您仍然想发送信号让其他对象远离,您可以使用单个初始下划线名称,带有初始下划线的名称不会通过带星号的导入导入(来自模块导入*)
示例:
输出-->
现在,如果我们手动调用 _hello 。
输出-->
最后:Python 并没有真正具有同等的隐私支持,尽管是单一的
首字母双下划线在某种程度上确实为您提供了两个级别的隐私
Python does not support privacy directly . Programmer need to know when it is safe to modify attribute from outside but anyway with python you can achieve something like private with little tricks.
Now let's see a person can put anything private to it or not.
Now When we will execute :
Then how someone can access that variable ???
You can do like :
wow , actually if python is getting any variable starting with double underscore are “translated” by adding a single underscore and the class name to the beginning:
Note : If you do not want this name changing but you still want to send a signal for other objects to stay away, you can use a single initial underscore names with an initial underscore aren’t imported with starred imports (from module import *)
Example :
output-->
Now if we will call _hello manually .
output-->
Finally : Python doesn’t really have an equivalent privacy support, although single
and double initial underscores do to some extent give you two levels of privacy
这可能有效:
This might work:
这是一个有点长的答案,但我认为它触及了真正问题的根源——可见范围。当我艰难地完成这个任务时,请坚持住!
简单地导入模块并不一定能让应用程序开发人员访问其所有类或方法;如果我实际上无法查看模块源代码,我如何知道可用的内容?有人(或某件事)必须告诉我我能做什么,并解释如何使用我被允许使用的功能,否则整件事对我来说毫无用处。
那些通过导入模块基于基本类和方法开发更高级别抽象的人会收到一份规范文档——而不是实际的源代码。
模块规范描述了客户端开发人员可见的所有功能。在处理大型项目和软件项目团队时,模块的实际实现应该始终对使用它的人隐藏——它是一个带有外部世界接口的黑匣子。对于 OOD 纯粹主义者来说,我认为技术术语是“解耦”和“连贯性”。模块用户只需要知道接口方法,而不必担心实现细节。
在没有首先更改其底层规范文档的情况下,切勿更改模块,这可能需要在某些组织中进行审查/批准才能更改代码。
作为业余程序员(现已退休),我启动了一个新模块,其中规范文档实际上写成模块顶部的巨大注释块,这将是用户在规范库中实际看到的部分。由于只有我一个人,所以我还没有建立一个库,但这很容易做到。
然后我开始编码,编写各种类和方法,但没有函数体——只有像“print()”这样的空打印语句——足以让模块编译而没有语法错误。当这一步完成后,我编译完成的空模块——这是我的规范。如果我在项目团队工作,我会提出这个规范/界面以供审查和使用。在继续充实身体之前进行评论。
我一次充实每个方法的主体并进行相应的编译,确保立即修复语法错误。这也是开始在底部编写临时“主”执行部分以在编码时测试每个方法的好时机。编码/测试完成后,所有测试代码都会被注释掉,直到您再次需要它(如果需要更新)。
在现实世界的开发团队中,规范注释块也会出现在文档控制库中,但那是另一回事了。要点是:作为模块客户端,您只能看到此规范,而不是源代码。
PS:早在时间开始之前,我就在国防航空航天社区工作,我们做了一些非常酷的事情,但是诸如专有算法和敏感系统控制逻辑之类的东西都在超级安全软件库中严格存储和加密。我们可以访问模块/包接口,但不能访问黑盒实现主体。有一个文档管理工具可以处理所有系统级设计、软件规格、源代码和测试记录——所有这些都同步在一起。政府对软件质量保证标准有严格的要求。有人记得一种叫做“Ada”的语言吗?我才多大岁数啊!
This is kinda a l-o-n-g answer but I think it gets to the root of the real problem here -- scope of visibility. Just hang in there while I slog through this!
Simply importing a module need not necessarily give the application developer access to all of its classes or methods; if I can't actually SEE the module source code how will I know what's available? Some one (or some THING) has to tell me what I can do and explain how to use those features I'm allowed to use, otherwise the whole thing is useless to me.
Those developing higher-level abstractions based on fundamental classes and methods via imported modules are presented with a specification DOCUMENT -- NOT the actual source code.
The module spec describes all the features intended to be visible to the client developer. When dealing with large projects and software project teams, the actual implementation of a module should ALWAYS remain hidden from those using it -- it's a blackbox with an interface to the outside world. For OOD purists, I believe the techie terms are "decoupling" and "coherence". The module user need only know the interface methods without being burden with the details of implementation.
A module should NEVER be changed without first changing its underlying spec document, which may require review / approval in some organizations prior to changing the code.
As hobby programmer (retired now), I start a new module with the spec doc actually written out as a giant comment block at the top of the module, this will be the part the user actually sees in the spec library. Since it's just me, I've yet to set up a library, but it would be easy enough to do.
Then I begin coding by writing the various classes and methods but without functional bodies -- just null print statements like "print()" -- just enough to allow the module to compile without syntax errors. When this step is complete I compile the completed null-module -- this is my spec. If I were working on a project team, I would present this spec/interface for review & commentary before proceeding with fleshing out the body.
I flesh out the bodies of each method one at a time and compile accordingly, ensuring syntax errors are fixed immediately on-the-fly. This is also a good time to start writing a temporary "main" execution section at the bottom to test each method as you code it. When the coding/testing are complete, all of the test code is commented out until you need it again should updates become necessary.
In a real-world development team, the spec comment block would also appear in a document control library, but that's another story. The point is: you, as the module client, see only this spec and NOT the source code.
PS: long before the beginning of time, I worked in the defense aerospace community and we did some pretty cool stuff, but things like proprietary algorithms and sensitive systems control logic were tightly vaulted and encrypted in super-duper secure software libraries. We had access to module / package interfaces but NOT the blackbox implementation bodies. There was a document management tool that handled all system-level designs, software specs, source code and test records -- it was all synched together. The government had strict requirements software quality assurance standards. Anyone remember a language called "Ada"? That's how old I am!
PEP 8
“方法名称和实例变量”部分 https://peps.python.org/pep-0008/#method-names-and-instance-variables
“为继承而设计”部分
“ https://peps.python.org/pep-0008/#designing -用于继承
PEP 8
Section "Method Names and Instance Variables" https://peps.python.org/pep-0008/#method-names-and-instance-variables
Section "Designing for Inheritance
" https://peps.python.org/pep-0008/#designing-for-inheritance
我使用 Python 2.7 和 3.5。我写了这段代码:
运行它并得到:
请参阅:
https://www.tutorialsteacher.com/python/ python 中的私有和受保护访问修饰符
I use Python 2.7 and 3.5. I wrote this code:
ran it and got:
Please see:
https://www.tutorialsteacher.com/python/private-and-protected-access-modifiers-in-python