Skip to Content
Python 3 Object-Oriented Programming - Third Edition
book

Python 3 Object-Oriented Programming - Third Edition

by Dusty Phillips
October 2018
Beginner to intermediate
466 pages
12h 2m
English
Packt Publishing
Content preview from Python 3 Object-Oriented Programming - Third Edition

The iterator protocol

The Iterator abstract base class, in the collections.abc module, defines the iterator protocol in Python. As mentioned, it must have a __next__ method that the for loop (and other features that support iteration) can call to get a new element from the sequence. In addition, every iterator must also fulfill the Iterable interface. Any class that provides an __iter__ method is iterable. That method must return an Iterator instance that will cover all the elements in that class.

This might sound a bit confusing, so have a look at the following example, but note that this is a very verbose way to solve this problem. It clearly explains iteration and the two protocols in question, but we'll be looking at several more readable ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python 3 Object-Oriented Programming - Second Edition

Python 3 Object-Oriented Programming - Second Edition

Dusty Phillips

Publisher Resources

ISBN: 9781789615852Supplemental Content