[Tutor] special attributes naming confusion

Steven D'Aprano steve at pearwood.info
Thu Jun 7 00:37:38 CEST 2012


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



More information about the Tutor mailing list