You learned about special methods earlier in this course and you explored a few of them already. Special methods are often closely associated with particular characteristics shared among data types within the same categories. In this lesson, you’ll briefly explore three special methods and the characteristics they’re linked to.
This text is taken from three different Real Python tutorials by Leodanis Pozo Ramos, Stephen Gruppetta, and Moshe Zadka.
Iterables and .__iter__()
When it comes to iteration in Python, you’ll often hear people talking about iterable objects or just iterables. To perform this iteration, you’ll often use a for loop. However, iteration also happens in other places in Python.
Many iterable objects typically hold the data themselves. For example, Python built-in container types—such as lists, tuples, dictionaries, and sets—are iterable objects. They provide a stream of data that you can iterate over. However, not all iterables contain data. Iterators are a different type of data structure that don’t contain their own data. Iterators are also iterable. Iterators won’t be covered further in this course.
Python expects iterable objects in several different contexts, the most common being for loops. Iterables are also expected in unpacking operations and in built-in functions, such as all(), any(), enumerate(), max(), min(), len(), zip(), sum(), map(), and filter().
The Iterable Protocol
The iterable protocol consists of a single special method, .__iter__(). This means that any class that has the .__iter__() special method defined creates iterable objects. This .__iter__() method must return an iterator object.
To quickly jump into an example of how the iterable protocol works, let’s look at a simple example of a class which contains a list as one of its data attributes. Here’s the implementation:
team.py
class Team:
def __init__(self, team_name, members):
self.team_name = team_name
self.members = list(members)
In this example, your Team class takes a string with the name of the team and a list with the team members. You can pass other iterables to the members parameter, but you ensure that the data attribute .members is a list by casting the input value to a list when you assign it to self.members.
Next, create a team and use this new Team object in a for loop: