Computing class variable on demand?

Steven Bethard steven.bethard at gmail.com
Thu Feb 3 01:36:51 EST 2005


fortepianissimo wrote:
> We all know that using __getattr__() we can compute an instance
> variable on demand, for example:
> 
> class Foo:
> def __getattr__ (self, name):
> if name == 'bar':
> self.bar = 'apple'
> return self.bar
> else:
> raise AttributeError()
> 
> Then we can
> 
> f = Foo()
> s1 = f.bar
> s2 = f.bar   # this uses the "cached" result
> 
> My question is can we do the same with class variables?

You can do this using a metaclass, e.g.:

py> class FooType(type):
...     def __getattr__(self, name):
...         if name == 'bar':
...             self.bar = 'apple'
...             return self.bar
...         else:
...             raise AttributeError('no attribute named %r' % name)
...
py> class Foo(object):
...     __metaclass__ = FooType
...
py> Foo.bar
'apple'

However, you probably don't want to.  What's your use case?

Steve



More information about the Python-list mailing list