'classmethod' object has only read-only attributes

Discussion in 'Python' started by Thomas Guettler, Nov 25, 2009.

  1. 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)


    --
    Thomas Guettler, http://www.thomas-guettler.de/
    E-Mail: guettli (*) thomas-guettler + de
    Thomas Guettler, Nov 25, 2009
    #1
    1. Advertising

  2. Thomas Guettler

    Peter Otten Guest

    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@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
    Peter Otten, Nov 25, 2009
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. keithb
    Replies:
    2
    Views:
    7,982
    keithb
    Jun 7, 2006
  2. Andrew Bennetts

    Re: __getitem__ and classmethod/staticmethod

    Andrew Bennetts, Jun 25, 2004, in forum: Python
    Replies:
    0
    Views:
    466
    Andrew Bennetts
    Jun 25, 2004
  3. Karl Chen
    Replies:
    0
    Views:
    316
    Karl Chen
    Jun 25, 2004
  4. Tim Chase
    Replies:
    2
    Views:
    318
    James Stroud
    Mar 15, 2006
  5. crystalattice
    Replies:
    2
    Views:
    359
    crystalattice
    Sep 1, 2006
Loading...

Share This Page