python的cached_property裝飾器

直接上源碼, 看一哈

英文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__中了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章