I'm trying to write a decorator similar to property, with the
difference that it applies to the defining class (and its subclasses)
instead of its instances. This would provide, among others, a way to
define the equivalent of class-level constants:
class Foo(object):
@classproperty
def TheAnswer(cls):
return "The Answer according to %s is 42" % cls.__name__
[color=blue][color=green][color=darkred]
>>> Foo.TheAnswer[/color][/color][/color]
The Answer according to Foo is 42[color=blue][color=green]
>> Foo.TheAnswer = 0[/color][/color]
exceptions.Attr ibuteError
....
AttributeError: can't set class attribute
I read the 'How-To Guide for Descriptors'
(http://users.rcn.com/python/download/Descriptor.htm) that describes
the equivalent python implementation of property() and classmethod()
and I came up with this:
def classproperty(f unction):
class Descriptor(obje ct):
def __get__(self, obj, objtype):
return function(objtyp e)
def __set__(self, obj, value):
raise AttributeError, "can't set class attribute"
return Descriptor()
Accessing Foo.TheAnswer works as expected, however __set__ is
apparently not called because no exception is thrown when setting
Foo.TheAnswer. What am I missing here ?
George
difference that it applies to the defining class (and its subclasses)
instead of its instances. This would provide, among others, a way to
define the equivalent of class-level constants:
class Foo(object):
@classproperty
def TheAnswer(cls):
return "The Answer according to %s is 42" % cls.__name__
[color=blue][color=green][color=darkred]
>>> Foo.TheAnswer[/color][/color][/color]
The Answer according to Foo is 42[color=blue][color=green]
>> Foo.TheAnswer = 0[/color][/color]
exceptions.Attr ibuteError
....
AttributeError: can't set class attribute
I read the 'How-To Guide for Descriptors'
(http://users.rcn.com/python/download/Descriptor.htm) that describes
the equivalent python implementation of property() and classmethod()
and I came up with this:
def classproperty(f unction):
class Descriptor(obje ct):
def __get__(self, obj, objtype):
return function(objtyp e)
def __set__(self, obj, value):
raise AttributeError, "can't set class attribute"
return Descriptor()
Accessing Foo.TheAnswer works as expected, however __set__ is
apparently not called because no exception is thrown when setting
Foo.TheAnswer. What am I missing here ?
George
Comment