Can __iter__ be used as a classmethod?

Michele Simionato mis6 at pitt.edu
Wed Mar 5 10:40:33 EST 2003


Alex Martelli <aleax at aleax.it> wrote in message news:<QB99a.7028$zo2.234863 at news2.tin.it>...
> Michele Simionato wrote:
>    ...
> > Anyway, I can emulate classmethods with regular methods in the
> > metaclass:
> > 
> >>>> class meta(type):
> > ...   def call_f(cls): cls.f() # a perverse way of calling f
> > ...   def f(cls): print "%s.f" % cls.__name__
> > 
> >>>> class A(object):
> > ...   __metaclass__ = meta
> > ...
> >>>> class B(A): pass #notice: B inherits the metaclass of A
> > ...
> > 
> >>>> A.call_f()
>  A.f
> >>>> B.call_f()
> > B.f
> 
> Not quite -- try A().call_f()... would work just fine if call_f
> were a static method, but won't work for a metaclass method.
> 
> Not a decisive advantage, but there can be some elegance in
> being able to call A.f() and A().f() similarly.
> 
> 
> Alex

True, but my point was that this very little convenience does not
justify (IMHO) the introduction of classmethods in the language.
There are two typical cases:

1) I want to be able to call A().f(). Then I can use a regular method
defined in A and inside the method I extract the class with type(self);

2) A is not meant to be instantiated, and I want to use the notation A.f().
Then I can define a regular method in the metaclass.

Then, there is a limit case, where f is defined in the metaclass of A,
but I want to call it from an instance of A. In this case it is enough 
to write type(A()).f().

Therefore in any case, simply by typing few characters more, I can emulate
the classmethod effect (if not the precise syntax and some subtility).

If Python had no metaclasses, I would think classmethods are useful; but
since Python has metaclasses, I think they are redundant and a possible
source of confusion.

Just my $0.02,

                                               Michele




More information about the Python-list mailing list