Prasad, Ramit wrote:
For instance, the __iter__() method is called by the iter() built-in.
It can also called by any other piece of code that needs to acquire an
iterator from a generic container object. There is no list of all
such pieces of code that could ever call the __iter__() method of your
A lot of times iter()/__iter__() are used implicitly and not explicitly.
So knowing that iter() specifically calls __iter__ is not as useful as
knowing *when* to implement __iter__(). For example,
for x in obj:
# this is an implicit call; works for collections or instance that
# implements __iter__()
pass
Not just __iter__. For loops work over anything that implements the iterator
protocol or the sequence protocol.
That is, for loops first try to build an iterator by calling __iter__, and if
that fails they try the sequence protocol obj[0], obj[1], obj[2], ...
As a general rule, except when you are writing your own classes and defining
__DoubleUNDERscore__ methods, you should (almost) never need to explicitly use
such dunder methods.
--
Steven
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor