我正在尝试使用pyv8
安全地在python中执行javascript代码。在一天结束时,我有一个javascript使用的对象,我希望隐藏几个字段。
我知道python没有封装(as explained in this question),但是,有没有办法使用__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
至于无法通过javascript执行with
,也无法调用__enter__
,因为该对象已被锁定"。
虽然看起来效率不高。还有更好的方法吗?
答案 0 :(得分:0)
您可以使用限制访问的属性getter吗?
try {
//do we even have this function?
typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
PGNSI pGNSI;
SYSTEM_INFO si;
ZeroMemory(&si, sizeof(SYSTEM_INFO));
pGNSI = (PGNSI) GetProcAddress( GetModuleHandle(TEXT("kernel32.dll")), "GetCurrentPackageFullName");
//ok this exists, now let's use it
if(pGNSI != NULL) {
//then I call the function here
}
} catch (int e) {
//do nothing, just don't crash
}
更多信息可以在这里找到: https://docs.python.org/3/library/functions.html#property