Created
September 10, 2015 13:41
-
-
Save ybastide/377ff45191e1234d0590 to your computer and use it in GitHub Desktop.
Cached property, also for static properties
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, or a class method into a property | |
cached on the class. | |
Adapted from django/utils/functional.py. | |
""" | |
def __init__(self, func): | |
self.func = func | |
def __get__(self, instance, typ): | |
obj = instance or typ | |
res = obj.__dict__[self.func.__name__] = self.func(obj) | |
return res | |
class Truc(object): | |
def __init__(self, v): | |
self.v = v | |
@cached_property | |
def chose_statique(self): | |
return 2+2 | |
@cached_property | |
def chose_dynamique(self): | |
return self.v | |
if __name__ == "__main__": | |
print Truc.chose_statique | |
truc = Truc(42) | |
print truc.chose_dynamique |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment