Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class T(object):
- """
- This class shows how to create dynamic attributes that are only processed when called directly for the first time.
- After the first call, it returns the previously fetched value.
- The dynamic attributes must be in the _dynamic dictionary and must have a processing method with the following name:
- get_<dynamic_attribute_name>(self)
- """
- def __init__(self):
- super(T, self).__init__()
- self.static = 1
- self._dynamic = {
- 'directed': None,
- 'wrote': None,
- 'performed': None,
- 'playsCharacter': None,
- }
- def __getattr__(self, name):
- if name in self._dynamic.keys():
- print '> In dynamic Keys'
- if not self._dynamic[name]:
- self._dynamic[name] = getattr(self, 'get_' + name)()
- return self._dynamic[name]
- else:
- return super(T, self).__getattribute__(name)
- def get_directed(self):
- print '> getting directed'
- return 'directed'
- def get_wrote(self):
- print '> getting wrote'
- return 'wrote'
- def get_performed(self):
- print '> getting performed'
- return 'performed'
- def get_playsCharacter(self):
- print '> getting character'
- return 'character'
- if __name__ == '__main__':
- print 'Running tests...\n'
- t = T()
- print '[static] Expecting 1:', t.static, '\n'
- print '--- Dynamic First Time ---\n'
- print '[dynamic - directed] First time:'
- print t.directed, '\n'
- print '[dynamic - wrote] First time:'
- print t.wrote, '\n'
- print '[dynamic - performed] First time:'
- print t.performed, '\n'
- print '[dynamic - playsCharacter] First time:'
- print t.playsCharacter, '\n'
- print '--- Dynamic Second Time ---\n'
- print '[dynamic - directed] Second time:'
- print t.directed, '\n'
- print '[dynamic - performed] Second time:'
- print t.performed, '\n'
- print '[dynamic - wrote] Second time:'
- print t.wrote, '\n'
- print '[dynamic - playsCharacter] Second time:'
- print t.playsCharacter, '\n'
- print '--- Static creation ---\n'
- t.second_static = 2
- print '[second_static] Expecting 2:', t.second_static, '\n'
- print '--- Attribute Error ---\n'
- try:
- print '[attribute_error] Expecting Exception:',
- print t.nonExisting, '\n'
- except AttributeError:
- print 'AttributeError Caught\n'
- print '--- Insanity Tests ---\n'
- print '[static] Expecting 1:', t.static, '\n'
- t.static = 0
- print '[static] Expecting 0:', t.static, '\n'
- print '[dynamic - directed] Third time:'
- print t.directed, '\n'
- print '\n--- Done! ---'
Add Comment
Please, Sign In to add comment