Iteration Over Class Instances Using __iter__
Solution 1:
Special methods like __iter__
are not looked up directly on the object, only on the type of the object. Python calls type(object).__iter__(object)
, not object.__iter__()
, effectively bypassing the normal object-first-then-type lookups (so from instance to class and from class to metaclass).
This is done to make hashing of types possible; if hash(object)
used the __hash__
method found directly on the object, you could never define a custom class with a __hash__
method for the instances.
The meta class is the type of the class; just like the class is the type of an instance, so iter(class)
looks for type(class).__iter__()
rather than at class.__iter__
directly.
If it did work that way, you could never define a __iter__
method for your class instances, because class.__iter__
would be a method and require the instance to be bound to, while there is no such instance if you are iterating over the class.
See the Special method lookup section of the Python datamodel documentation:
For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.
Solution 2:
Special method names are always invoked like this:
iter(foo) <--> type(foo).__iter__(foo)
Your first solution is compatible with this call (type(MyClass)
is the metaclass). Your second is not (type(MyClass1) is type
, which has no __iter__()
method).
Post a Comment for "Iteration Over Class Instances Using __iter__"