@cached_property

django.utils.functional 里发现的。

class cached_property(object):
    """
    Decorator that creates converts a method with a single
    self argument into a property cached on the instance.
    """
    def __init__(self, func):
        self.func = func

    def __get__(self, instance, type):
        res = instance.__dict__[self.func.__name__] = self.func(instance)
        return res

这玩意好用啊,比如

>>> class A(object):
...   @cached_property
...   def val(self):
...     print 'calc'
...     return 1
... 
>>> 
>>> a=A()
>>> a.val
calc
1
>>> a.val
1

以前自己山寨个 def val(): self._val = 什么的太烂了。

Comments