Can __iter__ be used as a classmethod?

Samuele Pedroni pedronis at bluewin.ch
Tue Mar 4 07:22:17 EST 2003


"Alex Martelli" <aleax at aleax.it> ha scritto nel messaggio
news:dv%8a.2507$pG1.64267 at news1.tin.it...
>
> In Python 2.2 and later (excepting, for backwards compatibility,
> 'classic classes') an operation always looks up the special methods
> of interest on the CLASS (aka type) of the object being operated on.
>

this is true (only exception is partially the static special method
__new__), OTOH looking at what the OP was trying to do it is seems that:

- the support  for both classmethods (ignored wrt to special methods) and
metatypes with their methods can be confusing

- people tend still to think in terms of the old model (that of classics
classes) which was purely a lookup-based one, so I presume they imagine
iter() as something like:

def iter(x):
  if hasattr(x,'__iter__'):
    iterator = x.iter()
    # check wheter iterator is such ...
   return iterator
  else: # seq case
    ...

but this absolutely not the case as you have explained (apart for __iter__
for classics classes).

Same for __add__:

>>> class C: pass
...
>>> c=C()
>>> c.__add__ = lambda x: "result=c+x"
>>> c+1
'result=c+x'
>>> class N(object): pass
...
>>> n=N()
>>> n.__add__ = lambda x: "result=n+x"
>>> n+1
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsupported operand types for +: 'N' and 'int'
>>> del n.__add__
>>> def Nadd(self,x): return "result=N+X"
...
>>> N.__add__=Nadd
>>> n+1
'result=N+X'







More information about the Python-list mailing list