Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def getValue(self, attributeName):
- if hasattr(self, attributeName):
- return getattr(self, attributeName)
- elif attributeName == 'A1':
- v = ... code to get value for A1
- self.A1 = v
- return v
- elif attributeName == 'A2':
- v = ... code to get value for A2
- self.A2 = v
- return v
- ....
- class cached_property(object):
- """Define property caching its value on per instance basis.
- Decorator that converts a method with a single self argument into a
- property cached on the instance.
- """
- def __init__(self, method):
- self.method = method
- def __get__(self, instance, type):
- res = instance.__dict__[self.method.__name__] = self.method(instance)
- return res
- class Foo:
- def __init__(self):
- # ordinary attributes
- self.B1 = something
- self.B2 = something_else
- @property
- def A1(self):
- try:
- return self._A1
- except AttributeError:
- self._A1 = ....calculate it....
- return self._A1
- foo = Foo()
- print foo.A1 # attribute calculated when first used
- print foo.A1 # this time, the value calculated before is used
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement