简体   繁体   English

如何拒绝在python中读取私有变量?

[英]How do I deny private variables from reading in python?

I am trying to execute javascript code in python, using pyv8 safely. 我试图安全地使用pyv8在python中执行javascript代码。 At the end of the day, I have an object being used by javascript, with few fields I would like to have hidden. 归根结底,我有一个JavaScript正在使用的对象,我想隐藏的字段很少。

I know python doesn't have encapsulation (as explained in this question) , but yet, is there a way to disable access using __getattribute__ ? 我知道python没有封装(如本问题所述) ,但是,有没有办法使用__getattribute__禁用访问?

class Context(object):
    def __init__(self, debug):
        self._a = ...
        self._b = ...
        self._c = ...
        self._unlocked = False

    def __enter__(self):
        self._unlocked = True

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._unlocked = False

    def __getattribute__(self, name):
        if object.__getattribute__(self, "_unlocked"):
            return object.__getattribute__(self, name)

        if name.startswith("_"):
            return None

        return object.__getattribute__(self, name)

So this object denies access to a "private" variables, unless unlocked using like this: 因此,除非使用以下方式解锁,否则该对象将拒绝访问“私有”变量:

ctx = Context()
...
with ctx:
   # _b is accessible here
   print ctx._b 

As far as there's no way to do with from javascript, nor to call __enter__ since the object is "locked". 至于有没有办法做到with从JavaScript,也不叫__enter__因为对象被“锁定”。

Seems not very efficient though. 似乎效率不是很高。 Is there a better way? 有没有更好的办法?

You could use a property getter that restricts access? 您可以使用限制访问的属性获取器吗?

class Context(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
    """I'm the 'x' property."""
        return "Property can not be accessed."

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

More info can be found here: https://docs.python.org/3/library/functions.html#property 可以在这里找到更多信息: https : //docs.python.org/3/library/functions.html#property

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM