Is There Any Way To Create A Class Property In Python?
The following doesn't work for some reason: >>> class foo(object): ... @property ... @classmethod ... def bar(cls): ... return 'asdf' ... >>
Solution 1:
If you want the descriptor property
to trigger when you get an attribute from object X, then you must put the descriptor in type(X)
. So if X is a class, the descriptor must go in the class's type, also known as the class's metaclass -- no "trickery" involved, it's just a matter of completely general rules.
Alternatively, you might write your own special-purpose descriptor. See here for an excellent "how-to" treaty on descriptors. Edit for example:
classclassprop(object):
def__init__(self, f):
self.f = classmethod(f)
def__get__(self, *a):
return self.f.__get__(*a)()
classbuh(object):
@classpropdefbah(cls): return23print buh.bah
emits 23
, as desired.
Post a Comment for "Is There Any Way To Create A Class Property In Python?"