Created
November 30, 2018 10:34
-
-
Save leafsummer/a229ff90be22277a3db4607037d81451 to your computer and use it in GitHub Desktop.
[python description for cache the property]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment