【发布时间】:2017-04-03 15:41:27
【问题描述】:
您好,我正在尝试创建一个表示可以使用 for ... in 循环迭代的区域的类。我知道这可以通过两个 for 循环来完成,但我试图从总体上理解生成器。
我正在使用 Python 3
我已经写了这个但不起作用:
class Area:
def __init__(self, width, height):
self.width = width
self.height = height
def __iter__(self):
# my best try, clearly I don't understand
# something about generators
for x in range(0, self.width):
for y in range(0, self.height):
yield x, y
area = Area(2, 3)
for x, y in area:
print("x: {}, y: {}".format(x, y))
# I want this to output something like:
# x: 0, y: 0
# x: 1, y: 0
# x: 0, y: 1
# x: 1, y: 1
# x: 0, y: 2
# x: 1, y: 2
谢谢你
【问题讨论】:
-
我尝试了您的代码,它几乎可以正常工作。究竟什么“不起作用”?
-
尝试只用两个
for循环迭代点,不涉及Area类。这可能会让你做错了什么更明显。 -
切换 for 循环。
-
谢谢大家,我想我的代码中还有另一个错误。我对我的问题进行了简化,这段代码有效。对不起,是我的错。
标签: python python-3.x iterator generator