python调用缺失属性时设置属性

0 投票
2 回答
595 浏览
提问于 2025-04-18 02:39

我有一个对象,这个对象有几个属性,这些属性的值查询起来比较慢。所以我不想在创建这个对象的时候就把所有属性的值都获取到,而是等到代码真正需要这些属性的时候再去获取,因为根据不同的代码路径,只需要其中的一部分属性。并且,我在代码中到达某些点的顺序也不是很确定,所以我不能在脚本的固定位置设置这些属性。因此,我打算创建一个方法

def getValue(self, attributeName):
    if hasattr(self, attributeName): 
        return getattr(self, attributeName)
    elif attributeName == 'A1':
        v = ... code to get value for A1
        self.A1 = v
        return v
    elif attributeName == 'A2':
        v = ... code to get value for A2
        self.A2 = v
        return v
    ....

但我在想,这样处理是否真的好,或者有没有更聪明的方法可以选择。谢谢大家的评论。

2 个回答

1

你可以像这样使用 Python 的属性

class Foo:
    def __init__(self):
        # ordinary attributes
        self.B1 = something
        self.B2 = something_else

    @property
    def A1(self):
        try:
            return self._A1
        except AttributeError:
            self._A1 = ....calculate it....
            return self._A1

然后你可以:

foo = Foo()
print foo.A1  # attribute calculated when first used
print foo.A1  # this time, the value calculated before is used
2

你可以使用这个装饰器:

class cached_property(object):
    """Define property caching its value on per instance basis.
    Decorator that converts a method with a single self argument into a
    property cached on the instance.
    """
    def __init__(self, method):
        self.method = method

    def __get__(self, instance, type):
        res = instance.__dict__[self.method.__name__] = self.method(instance)
        return res

这里

撰写回答