理解迭代器
在这一步中,你将从零开始创建一个简单的迭代器。迭代器是 Python“优美胜于丑陋”理念的核心。它们使你能够遍历集合(如列表或字典)中的元素,而无需知道集合的大小或结构。
让我们开始创建一个迭代器,它将遍历你最喜欢的未来派小工具列表。
在 ~/project/iterator_lab.py
Python 文件中包含以下代码:
## iterator_lab.py
class FavoriteGadgets:
def __init__(self, gadgets):
self.gadgets = gadgets
self.index = 0
def __iter__(self):
return self
def __next__(self):
try:
gadget = self.gadgets[self.index]
self.index += 1
return gadget
except IndexError:
raise StopIteration
## Create a collection of futuristic gadgets
gadgets_list = ["Cybernetic Exoskeleton", "Holographic Display", "Quantum Computer"]
## Making an iterator from the list
gadgets_iterator = FavoriteGadgets(gadgets_list)
## Iterate through the collection
for gadget in gadgets_iterator:
print(f"Gadget: {gadget}")
此代码块演示了如何在 Python 中实现迭代器。通过执行以下命令运行它:
python iterator_lab.py
你应该会看到以下输出:
Gadget: Cybernetic Exoskeleton
Gadget: Holographic Display
Gadget: Quantum Computer