'classmethod' object has only read-only attributes

Peter Otten __peter__ at web.de
Wed Nov 25 15:30:21 CET 2009


Thomas Guettler wrote:

> Hi,
> 
> why have classmethods only readonly attributes? It works for other
> methods.
> 
> exmpale code:
> {{{
> class Foo(object):
>     @classmethod
>     def bar(cls):
>         pass
>     bar.myattr='test'
> }}}
> 
> user at host:~> python ~/tmp/t.py
> Traceback (most recent call last):
>   File "/home/user/tmp/t.py", line 1, in <module>
>     class Foo(object):
>   File "/home/user/tmp/t.py", line 5, in Foo
>     bar.myattr='test'
> TypeError: 'classmethod' object has only read-only attributes (assign to
> .myattr)

No idea. But here's a workaround:

>>> class A(object):
...     def method(cls): print cls
...     method.foo = 42
...     method = classmethod(method)
...
>>> A.method()
<class '__main__.A'>
>>> A.method.foo
42

Or, going fancy:

>>> def attrs(**kw):
...     def set(obj):
...             for k, v in kw.iteritems():
...                     setattr(obj, k, v)
...             return obj
...     return set
...
>>> class A(object):
...     @classmethod
...     @attrs(foo=42)
...     def method(cls): print cls
...
>>> A.method()
<class '__main__.A'>
>>> A().method.foo
42

Peter




More information about the Python-list mailing list