Can __iter__ be used as a classmethod?

Giovanni Bajo noway at sorry.com
Tue Mar 4 19:46:51 CET 2003


"Michele Simionato" <mis6 at pitt.edu> ha scritto nel messaggio
news:2259b0e2.0303041023.43e8b81f at posting.google.com...

> It seems to me I could always use a regular method instead of
> a classmethod, by accessing the class trough self.__class__ or
> type(self), therefore classmethods only provide a very small amount
> of syntactical sugar.

Actually, they let you also call the method without any instance of the
class (they do not need to be bound to any instance).

> Actually they seems to me an unessential complication to the language,
> expecially because they are easily confused with the methods in the
> metaclass.

Yes:

class A(object):
    x = 10

    class __metaclass__(type):
        def f(cls):
            print "Hello from", cls, ", value is", cls.x

    def g(cls):
            print "Hello from", cls, ", value is", cls.x
    g = classmethod(g)

>>> A.g()
Hello from <class '__main__.A'> , value is 10
>>> A.f()
Hello from <class '__main__.A'> , value is 10

So for basic usage, you accomplished the same: you have a method in class A
that you can call without any instance of A, and can work on the attributes
of the class.
The only difference I can see is:

>>> a = A()
>>> a.g()
Hello from <class '__main__.A'> , value is 10
>>> a.f()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AttributeError: 'A' object has no attribute 'f'

This is because of the lack of transitivity in the 'inheritance' from types,
as explained by Alex in another post in this thread.

So, what are the other differences (if any)? Why do classmethods exist?

Giovanni Bajo






More information about the Python-list mailing list