property using a classmethod
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Fri Jul 10 06:14:26 EDT 2009
Lie Ryan a écrit :
> Bruno Desthuilliers wrote:
>> Lie Ryan a écrit :
>>> Emanuele D'Arrigo wrote:
>> (snip)
>>>> Ultimately all I want is a non-callable class-level attribute
>>>> MyClass.myProperty that gives the result of MyClass.myClassMethod().
>>> This works like what you seem to want (it's ugly):
>> Ugly, indeed. And an extreme case of arbitrary overcomplexification too :-/
>>
>> (snip rube goldberg code)
>>
>
> Can't think of anything simpler than that without meddling with
> descriptor.
Hmmm... Rereading the OP's spec, I guess you understood it better than I
did - seems the OP wants to be able to call the "property" on the class
object itself - which won't work with the builtin property type. So my
own proposed solution won't do :-/
But still, "meddling with descriptor" is *way* simpler than your
proposed solution. Here's a simple non-binding descriptor that do the job:
class ClsProperty(object):
def __init__(self, fget):
if not isinstance(fget, (classmethod, staticmethod)):
raise ValueError(
"fget must be a classmethod or staticmethod"
)
self.fget = fget
def __get__(self, obj, cls=None):
if cls is None:
assert obj is not None
cls = type(obj)
return self.fget.__get__(obj, cls)()
# example use
class Foo(object):
@classmethod
def bar(cls):
return "%s.bar" % cls.__name__
quux = ClsProperty(bar)
> I'm not even sure descriptor can help here as it seems
> descriptor needs an instance?
wrt/ descriptors, no, they don't "need" an instance, at least for
non-binding descriptors. Else, MyClass.MyMethod would return the
MyClass.__dict__['MyMethod'] function, not an unbound method object !-)
More information about the Python-list
mailing list