python的cachedproperty装饰器

31次阅读

共计 745 个字符,预计需要花费 2 分钟才能阅读完成。

直接上源码, 看一哈

英文 doc 的意思:

 每个实例只计算一次的属性,然后用普通属性替换自身。删除属性将重置属性。
class cached_property(object):
    """
    A property that is only computed once per instance and then replaces itself
    with an ordinary attribute. Deleting the attribute resets the property.
    Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76
    """  # noqa

    def __init__(self, func):
        self.__doc__ = getattr(func, "__doc__")
        self.func = func

    def __get__(self, obj, cls):
        if obj is None:
            return self
        value = obj.__dict__[self.func.__name__] = self.func(obj)
        return value

其实就保存到实例字典__dict__中, 避免多次调用重复计算

举个代码例子

class Test(object):

    test1 = 'aaa'
    def __init__(self):
        self.age = 20

    @cached_property
    def real_age(self):
        return self.age + 19


if __name__ == '__main__':
    t = Test()

    print t.real_age  # 39
    print t.__dict__  # {'real_age': 39, 'age': 20}, 不加装饰器就不存在__dict__中了

正文完
 0