[英]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.