在python中模拟私有变量
可能的重复:
python 中的私有成员
我确实想隐藏几个变量,因为它们不属于在我的班级之外。此外,所有这些未记录的变量都会使继承变得毫无用处。
如何隐藏不想在对象外部显示的变量?
为了澄清为什么我需要私有变量,首先举一个例子,其中无法隐藏变量只是一种不便,然后另一个例子确实是一个问题:
class MyObject(object):
def __init__(self, length):
self.length = length
def __len__(self):
return length
item = MyObject(5)
item.length
len(item)
所以我有两种方法来访问此处项目的“长度”。这只是一种不便,并没有什么可怕的。
from wares import ImplementationSpecific
class MyThing(object):
def __init__(self):
self.__no_access_even_if_useful = ImplementationSpecific()
def restricted_access(self):
return self.__no_access_even_if_useful.mutable_value
thing = MyThing()
thing.restricted_access()
thing._MyThing__no_access_even_if_useful.something_useful_for_someone()
所以说我有一天想改变实现。除非我真的隐藏了实现细节,否则它很可能会破坏某些东西。
我会把它当作任何人都可以编程的。 “任何人”都可以从我的实现细节中找到有用的东西并使用它,即使我强烈不鼓励这样做!直接说:“不,不存在,尝试别的东西”会容易得多。
Possible Duplicate:
private members in python
I've got few variables I really want to hide because they do not belong outside my class. Also all such non-documented variables render inheritance useless.
How do you hide such variables you don't want to show outside your object?
To clarify why I need private variables, first one example where inability to hide variables is just an inconvenience, then another that's really a problem:
class MyObject(object):
def __init__(self, length):
self.length = length
def __len__(self):
return length
item = MyObject(5)
item.length
len(item)
So I've got two ways to access 'length' of the item here. It's only an inconvenience and nothing horrible.
from wares import ImplementationSpecific
class MyThing(object):
def __init__(self):
self.__no_access_even_if_useful = ImplementationSpecific()
def restricted_access(self):
return self.__no_access_even_if_useful.mutable_value
thing = MyThing()
thing.restricted_access()
thing._MyThing__no_access_even_if_useful.something_useful_for_someone()
So say I want to change the implementation some day.. The chances are it'll break something unless I've really buried the implementation specifics.
I'll take it as anyone could program. That 'anyone' can find an useful thing from my implementation specifics and use it, even if I'd have strongly discouraged of doing so! It'd be much easier to just say: "no, it's not there, try something else."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Python 文档中介绍了私有变量:
摘要:在名称前使用下划线。
Private variables is covered in the Python documentation:
Summary: use an underscore before the name.
来自 Python 文档:
From the Python docs: