On 1/1/2011 6:55 PM, K. Richard Pixley wrote:
Can anyone explain to me why this doesn't work?

class Foo(object):
@property
@classmethod
def f(cls):
return 4

I mean, I think it seems to be syntactically clear what I'm trying to
accomplish. What am I missing?

First, because classmethod returns a classmethod instance, not a function, so what gets passed to property is the classmethod descriptor, not an actual callable.

Second, because a property descriptor just returns itself when accessed on the class. It only works on instances.

To do what you want, I think you would need to write your own descriptor class. Something like this:

class classproperty(object):

    def __init__(self, getter):
        self._getter = getter

    def __get__(self, instance, owner):
        return self._getter(owner)

class Foo(object):
    @classproperty
    def f(cls):
        return 4

Modify as needed if you want to accomodate setters and deleters as well.

Cheers,
Ian

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to