python 中的“交友”类
有没有什么方法可以使类中的某些变量成为“私有”(或任何 self.__var
真正的变量),但可以被另一个类访问,就像 c++ 中的朋友一样,除了 python 之外?我不希望任何一个类中的变量被弄乱。我也不想复制整个代码并将其转换为第二个类。
Is there any way to make certain variables in classes "private" (or whatever self.__var
really is) but be accessible to another class, like friends in c++, except in python? I do not want the variables in either class being messed with. Nor do I want to copy the entire code over and convert it for the second class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,没有这样的选择。
使用以单下划线开头的名称,并告诉参与您项目的其他人员不要对他们访问的内容感到愚蠢。
No, there is not such an option.
Use names that start with single underscores and tell the other people working on your project to not be silly about what they access.
Python 的哲学是访问控制之类的问题取决于程序员的纪律。它不会尝试用语言编码程序的哪些部分是内部实现细节,哪些部分是文档化接口的一部分。因此,它不需要像
friend
这样的构造来尝试声明程序的哪些其他部分是类实现的一部分,哪些只是客户端。这个想法是,如果你不能在不将这些概念部分编码到你的程序中的情况下编写/设计/记录/使用好的代码,那么当你对它们进行编码时你也可能无法做到这一点。因此,最好不要在语言中使用此类结构,因为它们不会增加语言的表达能力,有时还会造成妨碍。
The philosophy of Python is that issues like access control are up to programmer discipline. It doesn't attempt to encode in the language which parts of the program are internal implementation details, and which are part of the documented interface. Thus, it doesn't need constructs like
friend
to try to declare which other parts of the program are part of the implementation of a class and which are merely clients.The idea is that if you can't write/design/document/use good code without partially encoding these concepts into your program, you probably can't do it when you are encoding them either. Therefore it's better not to have such constructs in the language, since they don't increase the expressive power of the language and occasionally they get in the way.
python 中没有友元函数选项。
您可以选择使用单个下划线来定义受保护的变量,
但是在python中,受保护的变量也可以被主函数访问,但这并不完全是受保护变量的定义,看看吧。
there is no option of friend function in python.
you have an option to define a protected variable by using a single underscore,
but in python protected variable is also accessed by the main function, but this is not exactly the definition of a protected variable just have a look.
我不知道你在说什么。
I have no clue what you're talking about.