[英]How do I deny private variables from reading in python?
我试图安全地使用pyv8
在python中执行javascript代码。 归根结底,我有一个JavaScript正在使用的对象,我想隐藏的字段很少。
我知道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)
因此,除非使用以下方式解锁,否则该对象将拒绝访问“私有”变量:
ctx = Context()
...
with ctx:
# _b is accessible here
print ctx._b
至于有没有办法做到with
从JavaScript,也不叫__enter__
因为对象被“锁定”。
似乎效率不是很高。 有没有更好的办法?
您可以使用限制访问的属性获取器吗?
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
可以在这里找到更多信息: https : //docs.python.org/3/library/functions.html#property
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.