cached_property的使用

Posted on 2018-07-13 20:43  王将军之武库  阅读(1104)  评论(0编辑  收藏  举报

cached_property修饰过的函数,变成是对象的属性,该对象第一次引用该属性时,会调用函数,对象第二次引用该属性时就直接从词典中取了,这也说明引用属性是经过__getattritue__。

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, type=None):
        if instance is None:
            return self
        res = instance.__dict__[self.name] = self.func(instance)
        return res
class Monopoly(object):

    def __init__(self):
        self.boardwalk_price = 500

    @cached_property
    def boardwalk(self):
        # Again, this is a silly example. Don't worry about it, this is
        #   just an example for clarity.
        self.boardwalk_price += 50
        return self.boardwalk_price

monopoly = Monopoly()
print monopoly.boardwalk
print monopoly.boardwalk
print monopoly.boardwalk
del monopoly.__dict__['boardwalk']
print monopoly.boardwalk
print monopoly.boardwalk

输出为:

*** Remote Interpreter Reinitialized  ***
>>> 
550
550
550
600
600
>>> 

 

Copyright © 2024 王将军之武库
Powered by .NET 9.0 on Kubernetes