[Tutor] special attributes naming confusion

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


Dave wrote:
> I was reading some tutorial material on creating iterators. It shows the
> following example implementation of an iterator:
> 
> class Reverse:
>     """Iterator for looping over a sequence backwards."""
>     def __init__(self, data):
>         self.data = data
>         self.index = len(data)
>     def __iter__(self):
>         return self
>     def next(self):
>         if self.index == 0:
>             raise StopIteration
>         self.index = self.index - 1
>         return self.data[self.index]
> 
> 
> My question is how was I supposed to kinow that the function I call using
> the name iter() is implemented using the name __iter__()?

By reading the Fine Manual :)


Unless you are defining your own classes, you (almost) never need to care 
about __DoubleUNDERscore__ (dunder) methods and attributes. The main exception 
I can think of is the idiom for writing Python scripts:

if __name__ == '__main__':
     # Running as a script.
     main()
# Otherwise we're imported as a library.


Even when defining your own classes, simply define the methods you care about, 
such as __init__ for instance initialisation, but don't call __init__ 
directly. Python will call it for you. (Why keep a dog and bark yourself?)


> Is there a rule that describes when I would implement an attribute name
> with leading and trailing double underscores, and then call it without
> those underscores? How many names like this exist in Python? Are these
> special cases or is there a general rule that leading and trailing double
> underscores get dropped when calling functions that were implemented with
> these names? I'm trying to understand the big picture as far as how Python
> works when it comes to this situation. Thanks.

The big picture is that dunder methods are used for customizing operators and 
functions, but you really need to check the manual to see which operator maps 
to which dunder method.



-- 
Steven


More information about the Tutor mailing list