aleaxit at yahoo.com
Thu Aug 26 23:01:49 CEST 2004
Per Erik Stendahl <python-spam at berrs.net> wrote:
> Hello everyone,
> Is it possible to define "static properties" in a class?
Yes, but only by defining a custom metaclass to be the type of that
class. Properties are defined in the type, not in the instance; so, for
a class itself to have properties, the class's type, commonly known as
its metaclass, must be the one defining them.
>>> class metaPath(type):
... def curdir(cls): return os.getcwd()
... curdir = property(curdir)
>>> class Path: __metaclass__ = metaPath
>>> print Path.curdir
>>> print Path().curdir
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'Path' object has no attribute 'curdir'
if you want to be able to get at property curdir on INSTANCES of Path as
you normally would for a staticmethod, yet with property syntax, I think
you need to get a bit more clever than this... descriptors don't get
looked up two metalevels up, only one...
More information about the Python-list