property using a classmethod
Lie Ryan
lie.1296 at gmail.com
Thu Jul 9 08:37:30 EDT 2009
Emanuele D'Arrigo wrote:
> Greetings,
>
> today I did something like this:
>
> class MyClass(object):
>
> @classmethod
> def myClassMethod(self):
> print "ham"
>
> myProperty = property(myClassMethod, None, None)
>
> As many of you know this doesn't work and returns a TypeError: the
> object passed to the property is not a callable function but a
> classmethod object, which isn't callable at all.
That code runs fine for me. Although I doubt the behavior is what you
wanted to do.
> So, how do I do this?
> 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):
class MyClass(object):
class _MyClass(object):
@classmethod
def myClassMethod(cls):
return 'ham'
@property
def myProperty(self):
return MyClass._MyClass.myClassMethod()
@classmethod
def myClassMethod(cls):
return MyClass._MyClass.myClassMethod()
@property
def myProperty(self):
return MyClass._MyClass.myClassMethod()
def __call__(self, *args, **kargs):
# this is __init__
return MyClass._MyClass(*args, **kargs)
# note this is NOT a real MyClass instantiation
MyClass = MyClass()
$ python -i ./strangeclass.py
>>> MyClass.myClassMethod()
'ham'
>>> MyClass.myProperty
'ham'
>>> mc = MyClass()
>>> mc.myProperty
'ham'
>>> mc.myClassMethod()
'ham'
More information about the Python-list
mailing list