延迟加载属性

2024-05-16 12:17:22 发布

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

如何实现对象属性的延迟加载,也就是说,如果属性被访问但还不存在,则会调用一些应该加载这些属性的对象方法?在

我的第一次尝试是

def lazyload(cls):
    def _getattr(obj, attr):
        if "_loaded" not in obj.__dict__:
            obj._loaded=True
            try:
                obj.load()
            except Exception as e:
                raise Exception("Load method failed when trying to access attribute '{}' of object\n{}".format(attr, e))
            if attr not in obj.__dict__:
                AttributeError("No attribute '{}' in '{}' (after loading)".format(attr, type(obj))) # TODO: infinite recursion if obj fails
            return getattr(obj, attr)
        else:
            raise AttributeError("No attribute '{}' in '{}' (already loaded)".format(attr, type(obj)))

    cls.__getattr__=_getattr
    return cls

@lazyload
class Test:
    def load(self):
         self.x=1

t=Test()     # not loaded yet
print(t.x)   # will load as x isnt known yet

我将使lazyload仅特定于某些属性名。 由于我还没有做太多的元分类,我不确定这是否是正确的方法。 你有什么建议?在


Tags: 对象inobjformatif属性defnot