'classmethod' object has only read-only attributes

T

Thomas Guettler

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@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)
 
P

Peter Otten

Thomas said:
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@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:
.... def method(cls): print cls
.... method.foo = 42
.... method = classmethod(method)
....42

Or, going fancy:
.... def set(obj):
.... for k, v in kw.iteritems():
.... setattr(obj, k, v)
.... return obj
.... return set
........ @classmethod
.... @attrs(foo=42)
.... def method(cls): print cls
....42

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top