aleaxit at yahoo.com
Fri Aug 27 08:45:43 CEST 2004
Bengt Richter <bokr at oz.net> wrote:
> >> 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 ...
Hmmm -- I think we're talking somewhat at cross-purposes between
property, the built-in type, and the effect it has (that accessing an
attribute runs some code). I was focusing on the formed, but you're
quite right regarding the latter.
> >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:
If you don't use property, but "get a bit more clever" by defining a
custom descriptor as you have, yes:
> >>> class Path(object):
> ... class curdir(object):
> ... def __get__(self, inst, cls): return os.getcwd()
> ... curdir = curdir()
Nice. Unfortunately it doesn't extend to data properties, those with a
>>> class Path(object):
... class foo(object):
... def __get__(*a): return 'gotten'
... def __set__(*a): print 'setten'
... foo = foo()
>>> Path.foo = 23
I think (I hope I'm wrong) that to catch 'Path.foo = something' you do
have to use a custom metaclass (not 'metaclass magic', nothing in the
least magical about it). But if you're simply willing to trust users to
just never assign to Path.foo -- you don't need for such assignments to
cause an error nor for them to cause any specific action -- a simple
custom descriptor may indeed suffice.
More information about the Python-list