cached_property的使用

时间:2018-07-13 21:09:29   收藏:0   阅读:1603

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
>>> 

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!