Can __iter__ be used as a classmethod?
noway at sorry.com
Tue Mar 4 14:10:55 CET 2003
"Alex Martelli" <aleax at aleax.it> ha scritto nel messaggio
news:n519a.3620$zo2.111194 at news2.tin.it...
> E.g., if X is a class, X.__iter__ affects iterations on INSTANCES
> of X, *NOT* iterations on X itself;
> the latter are instead affected
> by type(X).__iter__, if any. type(X) is X's metaclass -- unless
> it's a custom one, type(X) will be the built-in named 'type', which
> has no special method __iter__.
Let's talk about new-style classes only (otherwise I could blow a fuse
before I understand something ;)
Is it possible to add (class) methods to class objects by defining them in a
custom metaclass, or is the metaclass used only to lookup special methods
(__iter__, etc.) for operations executed on class objects? Since I define
methods of the instances within the class (object's type) definition, I
would think that I might define methods of the class objects within the
metaclass (class' type) definition.
__iter__ = classmethod(__iter__)
how do you classify (word joke not intended) the (rebound) __iter__? Is it a
class method of class A? Is it still used for iterations on instances of A?
How does the classmethod() affected the type and the semantic of __iter__?
>Attributes that you look up on a specific object are not the
>same thing as special-methods that are looked up (on the TYPE
>of the object -- except for classic classes) by operations
>that you perform on the object. Normal method calls use normal
Probably I'm confused because to me:
f and __iter__ seems to be of the same kind (type). But you say that B().f()
is doing a lookup on the specific instance (and the lookup resolves to B.f),
while iter(B()) is looked up on the TYPE of the object, but it resolves to
B.__iter__ as well. So, if the lookup are performed on different entities,
why do they resolve in the same way? Is it just because they are not rebound
after the instance is created? Would that mean that rebinding B().__iter__
has no effect since B.__iter__ is always looked up when iterating over
instances of B(), while B().f() can be freely rebound?
More information about the Python-list