Confused with classmethods

jfj jfj at freemail.gr
Fri Mar 11 17:57:53 EST 2005


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





More information about the Python-list mailing list