Advertisement
Guest User

Untitled

a guest
Apr 18th, 2014
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. def getValue(self, attributeName):
  2. if hasattr(self, attributeName):
  3. return getattr(self, attributeName)
  4. elif attributeName == 'A1':
  5. v = ... code to get value for A1
  6. self.A1 = v
  7. return v
  8. elif attributeName == 'A2':
  9. v = ... code to get value for A2
  10. self.A2 = v
  11. return v
  12. ....
  13.  
  14. class cached_property(object):
  15. """Define property caching its value on per instance basis.
  16. Decorator that converts a method with a single self argument into a
  17. property cached on the instance.
  18. """
  19. def __init__(self, method):
  20. self.method = method
  21.  
  22. def __get__(self, instance, type):
  23. res = instance.__dict__[self.method.__name__] = self.method(instance)
  24. return res
  25.  
  26. class Foo:
  27. def __init__(self):
  28. # ordinary attributes
  29. self.B1 = something
  30. self.B2 = something_else
  31.  
  32. @property
  33. def A1(self):
  34. try:
  35. return self._A1
  36. except AttributeError:
  37. self._A1 = ....calculate it....
  38. return self._A1
  39.  
  40. foo = Foo()
  41. print foo.A1 # attribute calculated when first used
  42. print foo.A1 # this time, the value calculated before is used
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement