“Friend”ing classes in python

元气小坏坏 提交于 2019-12-18 19:09:24

问题


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.


回答1:


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.




回答2:


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.




回答3:


I have no clue what you're talking about.

>>> class Foo(object):
...   __bar = 42
... 
>>> class Quux(object):
...   def spam(self):
...     print Foo._Foo__bar
... 
>>> q = Quux()
>>> q.spam()
42


来源:https://stackoverflow.com/questions/6338867/friending-classes-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!