Re: Confused with classmethods

From: jfj (jfj_at_freemail.gr)
Date: 03/11/05


Date: Fri, 11 Mar 2005 14:57:53 -0800
To: python-list@python.org

Diez B. Roggisch wrote:

>>I understand that this is a very peculiar use of
>>classmethods but is this error intentional?
>>Or did I completely missed the point somewhere?
>
>
>
> A little bit: classmethods are defined in a class context.
>
> def foo(cls):
> print cls
>
> class A:
> foo = classmethod(foo)
>
> The error you observe seems to be a result of your "abuse" of classmethod
> outside a class scope.
>

Not necessarily:

def foo(cls):
     print cls
f=classmethod(foo)

class A: pass

A.f = f
a=A()
a.f()

This works. Anyway, the confusion starts from the documentation of
classmethod(). Since classmethod is a *function* of builtins we can
invoke it as such from wherever we want. Moreover the documentation
sais that if the first argument is an instance, its class will be
used for the classmethod. OTOH, "class scope" is not a real thing in
python. It is just some code which is executed and then we get its
locals and use it on Class(localsDict, BasesTuple, ClassName) to make
a new class, it seems. So we can create a classmethod in any scope
and then just attach it to a class's dictionary.

jf



Relevant Pages

  • Re: classmethod and instance method
    ... the instance details ... achieved using a second decorator in addition to the @classmethod. ... def instancemethod: ...
    (comp.lang.python)
  • classmethod and instance method
    ... the instance details ... achieved using a second decorator in addition to the @classmethod. ... def instancemethod: ...
    (comp.lang.python)