[python]@cached_property緩存裝飾器


cached_property緩存裝飾器

class cached_property(object):
    """
    Decorator that converts a method with a single self argument into a
    property cached on the instance.
    Optional ``name`` argument allows you to make cached properties of other
    methods. (e.g.  url = cached_property(get_absolute_url, name='url') )
    """
    def __init__(self, func, name=None):
        self.func = func
        self.__doc__ = getattr(func, '__doc__')
        self.name = name or func.__name__
 
    def __get__(self, instance, cls=None):
        if instance is None:
            return self
        res = instance.__dict__[self.name] = self.func(instance)
        return res

cached_property主要實現的功能是,user.getWorkYear第一次會進行計算,計算完之后把實例user的__dict__['getWorkYear']設置為計算后的值。下次讀值的時候會直接從__dict__['getWorkYear']取結果,避免了多次計算。
使用限制:只能用於只帶默認參數的類

不使用的例子

class User(object):
    def __init__(self, age=0):
        self.age=age
    
    def getWorkYear(self):
        return 65-self.age


user=User(20)
print(user.getWorkYear)     #<bound method User.getWorkYear of <__main__.User object at 0x00000000031A3C88>>
print(user.getWorkYear())   #45
print(user.__dict__)  #{'age': 20}
print(user.getWorkYear) #<bound method User.getWorkYear of <__main__.User object at 0x00000000031A3C88>>

使用的例子

from django.utils.functional import cached_property

class User(object):
    def __init__(self, age=0):
        self.age=age

    @cached_property
    def getWorkYear(self):
        return 65-self.age


user=User(20)
print(user.getWorkYear)    #45
print(user.getWorkYear())  #error
print(user.__dict__)  #{'age': 20, 'getWorkYear': 45}
print(user.getWorkYear) #45

user.getWorkYear -> __get__ -> 從實例字典(user.dict`獲取 -> 如果沒有則保存到字典並調用實際方法返回


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM