简体   繁体   中英

How do I deny private variables from reading in python?

I am trying to execute javascript code in python, using pyv8 safely. At the end of the day, I have an object being used by javascript, with few fields I would like to have hidden.

I know python doesn't have encapsulation (as explained in this question) , but yet, is there a way to disable access using __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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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