Can __iter__ be used as a classmethod?

Michele Simionato mis6+ at pitt.edu
Tue Mar 4 16:41:15 EST 2003


From: Bjorn Pettersen

> From: Michele Simionato [mailto:mis6 at pitt.edu] 
> [...]
> Is there any good reason for supporting classmethods in Python ?

> Yes, classmethods can do everything staticmethods can, plus
>polymorphism. E.g.:

>>> class meta(type):
...   def call_f(cls): cls.f()
...
>>> class A(object):
...   __metaclass__ = meta
...   def f(cls): print 'A.f'
...   f = classmethod(f)
...
>>> class B(object):
...   __metaclass__ = meta
...   def f(cls): print 'B.f'
...   f = classmethod(f)
...
>>> A.call_f()
A.f
>>> B.call_f()
B.f
>>>

This code does not make a good example for classmethods, since
it can be rewritten by using staticmethods (the knowledge of cls
is not used in f). 

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

> Digressing: It never occurred to me that assignment to __metaclass__ was
> defining the class of your class until it was pointed out earlier today.
> That made everything much clearer :-)
>
> -- bjorn

You may find interesting this article:

http://www-106.ibm.com/developerworks/linux/library/l-pymeta.html

-- 
Michele Simionato - Dept. of Physics and Astronomy
210 Allen Hall Pittsburgh PA 15260 U.S.A.
Phone: 001-412-624-9041 Fax: 001-412-624-9163
Home-page: http://www.phyast.pitt.edu/~micheles/





More information about the Python-list mailing list