Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python

'classmethod' object has only read-only attributes

 

 

Python python RSS feed   Index | Next | Previous | View Threaded


hv at tbz-pariv

Nov 25, 2009, 6:06 AM

Post #1 of 2 (143 views)
Permalink
'classmethod' object has only read-only attributes

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] hos:~> 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)


--
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de
--
http://mail.python.org/mailman/listinfo/python-list


__peter__ at web

Nov 25, 2009, 6:30 AM

Post #2 of 2 (138 views)
Permalink
Re: 'classmethod' object has only read-only attributes [In reply to]

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] hos:~> 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

--
http://mail.python.org/mailman/listinfo/python-list

Python python RSS feed   Index | Next | Previous | View Threaded
 
 


Interested in having your list archived? Contact Gossamer Threads
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.