全局范围内的描述符?

2024-09-19 20:49:00 发布

您现在位置:Python中文网/ 问答频道 /正文

python2.6中的descriptor protocol只为类定义而定义,因此只能由实例使用。在

是否有一些等效的方法来检测get/set全局参数?在

我正在尝试加速导入与主机系统交互的模块,因此必须对主机执行一些昂贵的探测。(昂贵)探测的结果存储在一个全局模块中,该模块在导入时初始化;所以我试图将初始化延迟到绝对需要的时候。在

拜托,不要评论环球人是邪恶的。我知道它们是什么以及何时使用它们。在

我当前的计划是创建一个使用描述符的全局实例,并将所有当前全局变量移动到该实例的属性中。我想这会管用的,我只是想问问有没有别的办法。在


Tags: 模块实例方法参数get定义系统评论
2条回答

如果你真的想这么做,这个链接提供了一个非常酷的方法来实现。唯一的警告是必须使用eval/exec/execfile执行代码。在

https://mail.python.org/pipermail/python-ideas/2011-March/009657.html

class MyDict:
    def __init__(self, mapping):
        self.mapping = mapping
    def __getitem__(self, key):
        value = self.mapping[key]
        if hasattr(value, '__get__'):
            print('Invoking descriptor on', key)
            return value.__get__(key)
        print('Getting', key)
        return value
    def __setitem__(self, key, value):
        self.mapping[key] = value

class Property:
    def __init__(self, getter):
        self.getter = getter
    def __get__(self, key):
        return self.getter(key)

if __name__ == '__main__':   
    md = MyDict({})
    md['x'] = 10
    md['_y'] = 20
    md['y'] = Property(lambda key: md['_'+key])
    print(eval('x+y+1', {}, md))

虽然有点笨重,但我觉得这很酷。在

My current plan is to create a global instance that uses descriptors, and move all my current globals into the attributes of this instance. I expect this will work; I'm just asking if there's another way.

这正是我要做的。在类之外没有等价的描述符。在

另一个选项,我有时也会用到,是使用函数而不是变量名,如下所示:

_expensive_to_compute = None
def get_expensive_to_compute():
    global _expensive_to_compute
    if _expensive_to_compute is None:
        _expensive_to_compute = do_computation()
    return _expensive_to_compute

如果您已经在某处定义了一个@memoize修饰符,那么可以大大简化上面的工作。在

相关问题 更多 >