Skip to content

Instantly share code, notes, and snippets.

@chaobin
Created April 9, 2013 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chaobin/5343371 to your computer and use it in GitHub Desktop.
Save chaobin/5343371 to your computer and use it in GitHub Desktop.
class NamedAndCachedAttributeType(type):
'''
In cases, where getting an attribute will
expose to the client code the detail of
the very attribute name, which could be changeable
over time.
This NamedAndCachedAttributeType is intended to
hide this detail by mapping the public attribute name
to the real name that is maintained internally by the class itself.
By doing so, the content provider(this class) and the client
code(the caller) establish a deal that the changes of names
are taken care of by the provider itself.
Second, the value is set as a class variable once it is
first retrieved, as being cached.
'''
def _raise(cls, name):
'''
Override this provide a more specific exception
'''
raise AttributeError('No name "%s" is found' % name)
def _cache(cls, name, value):
'''
The value will be cached by setting
it as the class variable
'''
setattr(cls, name, value)
def _get_value(cls, name):
'''
Override this method to do the
actual work of getting the value
'''
raise RuntimeError('_get_value() must be overridden')
def __getattr__(cls, name):
if cls.__dict__.has_key(name):
return cls.__dict__[name]
value = cls._get_value(name)
cls._cache(name, value)
return value
def test():
class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment