在python中模拟私有变量 [英] simulate private variables in python

查看:60
本文介绍了在python中模拟私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
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."

推荐答案

私有变量包含在 Python 文档:

Private variables is covered in the Python documentation:

9.6.私有变量

除了从对象内部之外无法访问的私有"实例变量在 Python 中不存在.但是,大多数 Python 代码都遵循一个约定:带有下划线前缀的名称(例如 _spam)应该被视为 API 的非公开部分(无论是函数、方法还是数据成员).它应被视为实施细节,如有更改,恕不另行通知.

"Private" instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

总结:在名称前使用下划线.

Summary: use an underscore before the name.

这篇关于在python中模拟私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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