2

我想实现变量的延迟加载,但我似乎有点误解了描述符。我想要对象变量,它在第一次访问时将调用 obj.load() 函数,该函数将使用它们的真实值初始化变量。我写

class ToLoad(object):
    def __init__(self, loader_name="load")
        self.loader_name=loader_name

    def __get__(self, obj, type):
        if not (hasattr(obj, "_loaded") and obj._loaded):
            obj._loaded=True
            getattr(obj, self.loader_name)()
        return None

class Test(object):
    x=ToLoad()
    def __init__(self, y):
        self.y=y

    def load(self):
        print("Loading {}".format(self.y))
        self.x=self.y

t1=Test(1)
t2=Test(2)
print("A", t1.x)
print("B", t2.x)
print("C", t1.x)

至少在第一次加载时无法返回实际值。有人可以提出另一种解决该问题的方法吗?我不确定如何在get中返回正确的值,因为那时我不知道该属性称为“x”?还有什么办法吗?

该死,无法回答我自己的问题......所以这里是编辑:感谢您的输入!但是,我的 load() 函数不返回变量本身,因为它加载了许多不同的变量。我想尽量减少使用延迟加载的符号。所以我想出了一个装饰器

class to_load:
    def __init__(self, *vars, loader="load"):
        self.vars=vars
        self.loader=loader

    def __call__(self, cls):

        def _getattr(obj, attr):
            if attr in self.vars:
                getattr(obj, self.loader)()
                return getattr(obj, attr)
            else:
                raise AttributeError

        cls.__getattr__=_getattr
        return cls

@to_load("a", "b")
class Test:
    def load(self):
        print("Loading")
        self.a=1
        self.b=2

t=Test()
print("Starting")
print(t.a)
print(t.b)
#print(t.c)

那样行吗?我不确定我是否在破坏东西。

4

2 回答 2

1

好吧,这里有两个问题:

  1. None从中返回__get__,而它应该是您要x表示的值。
  2. 你这样做x = y了,但你的描述符没有实现__set__

因此,与其设置“已加载”标志,不如创建一个具有实际值的属性,并检查它。如果你不希望它是只读的,你应该实现__set__. 否则,而不是self.x = self.yin load,返回值并让我们__get__处理分配。

class ToLoad(object):
    def __init__(self, var, func):
        self.var  = var
        self.func = func

    # style note: try to avoid overshadowing built-ins (e.g. type)
    def __get__(self, obj, cls):
        try:
            return getattr(obj, self.var)
        except AttributeError:
            value = getattr(obj, self.func)()
            setattr(obj, self.var, value)
            return value

class Foo(object):
    x = ToLoad('x', '_load_x')

    def __init__(self, y):
        self.y = y

    def _load_x(self):
        print('Loading {0} into x'.format(self.y))
        return self.y

a = Foo(1)
b = Foo(2)
print(a.x)
print(b.x)
print(a.x)
于 2011-08-25T17:41:31.010 回答
0

你想要的可能更像这样:

class Test(object):

    def __init__(self, y):
        self.y=y

    def __getattr__(self, attr):
        return self.load(attr)

    def load(self, attr):
        print("Loading `{}`".format(attr)) # ie "Loading `x`"
        # get the value for `attr` somewhere, here always self.y 
        val = self.y
        # store it on this object to avoid reloading it
        setattr(self, attr, val) 
        return val

t1=Test(1)
t2=Test(2)
print("A", t1.x)
print("B", t2.x)
print("C", t1.x)

要使您的代码正常工作,您需要几个return

class ToLoad(object):
    def __init__(self, loader_name="load"):
        self.loader_name=loader_name

    def __get__(self, obj, type):
        if not (hasattr(obj, "_loaded") and obj._loaded):
            obj._loaded=True
            return getattr(obj, self.loader_name)()
        return None

class Test(object):
    x=ToLoad()
    def __init__(self, y):
        self.y=y

    def load(self):
        print("Loading {}".format(self.y))
        self.x=self.y
        return self.x

t1=Test(1)
t2=Test(2)
print("A", t1.x)
print("B", t2.x)
print("C", t1.x)

描述符知道它们存储在哪个对象上,但不知道存储在哪个属性上。你想拦截一​​个属性的访问,而不是改变返回值,所以你想要__getattr__的不是描述符。

于 2011-08-25T17:40:41.600 回答