Can __iter__ be used as a classmethod?

Samuele Pedroni pedronis at bluewin.ch
Tue Mar 4 17:21:16 EST 2003


"Alex Martelli" <aleax at aleax.it> ha scritto nel messaggio
news:4B89a.6715$zo2.218162 at news2.tin.it...
> > So, what are the other differences (if any)? Why do classmethods exist?
>
> Aren't these reasons enough?  How else would you code a method that
> you can indifferently call either on any instance or on the class
> object itself?  And _having_ to write a custom metaclass as the
> only way to get classmethods would be somewhat of an overkill.

the existence discussion is moot, they are anyway a possibility of the
descriptors design:

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

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".






More information about the Python-list mailing list