Can __iter__ be used as a classmethod?

Michele Simionato mis6 at pitt.edu
Wed Mar 5 11:55:14 EST 2003


"Samuele Pedroni" <pedronis at bluewin.ch> wrote in message news:<3e65273f$1_3 at news.bluewin.ch>...

> import new
> 
> class myclassmethod(object):
>     __debug = 0
> 
>     def __init__(self,f):
>         self.__f = f
> 
>     def __get__(self,obj,typ=None):
>         if self.__debug:
>             print "MYCM__get__",obj,typ
> 
>         if typ is None:
>             typ = type(obj)
> 
>         return new.instancemethod(self.__f,typ,type(typ))
> 
> class C(object):
>     def g(cls):
>         print cls
> 
>     g = myclassmethod(g)
> 
> class D(C):
>     def g(cls):
>         print 'Dg',cls
>         C.g()
> 
>     g = myclassmethod(g)
> 
> This can be used as an argument to have them explicitely (you can implement
> them anyway, so let's get them right once and for all) or to not have them
> (who need them can cook them up).

In my view this is an argument against them.

> It is worth to notice that once you override one of them (like g in D
> overriding g in C) it is impossible to call in a clean way the parent
> version (C g) passing the derived class (D), which is what would happen in
> case of no overriding (if D would not define g, then D.g() would call g in C
> passing D), (so above C.g() obviously is calling g in C passing C). "Let's
> call this their price".

It seems to me that

class D(C):
    def g(cls):
        print 'Dg',cls
        C.g.im_func(cls)


works under 2.3 (and also super(D,cls).g.im_func(cls) would work). 

What surprised me, is that for staticmethods I can extract the wrapped
function with .__get__(None):

>>> def f(x): return x
...
>>> s=staticmethod(f)
>>> s.__get__(None)
<function f at 0x402c2534> # okay, here it is the original f

whereas for classmethods I have a quite different result:

>>> c=classmethod(f)
>>> c.__get__(None)
<bound method type.f of <type 'NoneType'>>

In a sense, staticmethods are really functions, whereas classmethods are
really methods. However, I wonder if there is a direct way to extract f 
from the classmethod ?


                                     Michele




More information about the Python-list mailing list