class level properties

Arnaud Delobelle arnodel at googlemail.com
Sun Apr 13 02:06:29 EDT 2008


On Apr 13, 12:33 am, Charles D Hixson <charleshi... at earthlink.net>
wrote:
> Arnaud Delobelle wrote:
> >>>> class MetaX(type):
>
> > ...     @property
> > ...     def spam(self): return 'eggs'
> > ...
>
> >>>> class X(object):
>
> > ...      __metaclass__ = MetaX
> > ...
>
> >>>> X.spam
>
> > 'eggs'
>
> > HTH
>
> > --
> > Arnau
>
> Thanks.  I can make that work.  Is it possible to move the entire
> implementation of the interpretation of  _valueMap, below, into
> properties in some similar way?  I'm referring to the part managed by
> __getattr__ below.
> I want a hundred or so read-only variables, and I'm not sure the best
> way to achieve it.

[snip code sample]

* Do you want to be able to access your attributes from instances as
well or from the class object only? The metaclass trick creates
attributes only accessible from the class object, i.e. in my example
above:

>>> x=X()
>>> x.spam
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'X' object has no attribute 'spam'

* If you have a hundred of so names and values, are you sure you want
to expose them as attributes?  It seems to me that they should be in
their own namespace (as keys in a mapping or attributes of a
subobject)

--
Arnaud




More information about the Python-list mailing list