Static properties
Bengt Richter
bokr at oz.net
Fri Aug 27 01:54:08 EDT 2004
On Thu, 26 Aug 2004 23:01:49 +0200, aleaxit at yahoo.com (Alex Martelli) wrote:
>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.
Um, UIAM a property is just a peculiar descriptor, which you can define
without resorting to metaclass magic. See below ...
>
>
>>>> class metaPath(type):
>... def curdir(cls): return os.getcwd()
>... curdir = property(curdir)
>...
>>>> class Path: __metaclass__ = metaPath
>...
>>>> print Path.curdir
>/Users/alex/cb/dblite/dblite_0.5
>
>
>_However_...:
>
>>>> 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...
>
But you only need one:
>>> class Path(object):
... class curdir(object):
... def __get__(self, inst, cls): return os.getcwd()
... curdir = curdir()
...
>>> import os
>>> Path.curdir
'C:\\pywk\\clp'
>>> Path().curdir
'C:\\pywk\\clp'
I wonder if I'll beat you to this post ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list