我想用类似迭代器的对象获取“下一个 Assets ”,但是(而不是 __next__()
方法)有两种算法加载下一个 Assets (next1
和下面的 next2
),它可以实现为“准迭代器”,例如:
class AssetLoader(object):
def __init___(self):
pass
def next1(self):
# ...
def next2(self):
# ...
要清楚,下一个检索到的对象是什么可能取决于调用 next1
和 next2
的“历史记录”,例如:
next1()
; 下一个()
; 下一个()
; 下一个()
; next2()
我的问题:这个(迭代器中的两种“下一步”)可以实现为生成器函数吗?
我想这可以通过函数引用的全局变量来完成。但是可以不使用全局变量而是使用一些局部变量来完成吗?
如果当前的 Python 很难或不可能,我们能否讨论如何向 Python 添加新的语义以使其成为可能?
最佳答案
这是一个使用send
在两种不同的迭代模式之间切换生成器的简单示例:它要么增加其当前值,要么将其相乘。同样的原则可以应用于您的图形遍历任务。
send
方法允许您将对象发送到生成器中。令人讨厌的是,send
的结果是您通过调用 next
获得的当前值;如果您可以在生成器不产生值的情况下发送,那就太好了,但这只是我们必须忍受的事情。
def add_or_mul(current, step, scale, mode='add'):
''' A generator that either adds step to the current value,
or multiplies it by scale
'''
while True:
newmode = yield current
if newmode is not None:
if newmode not in ('add', 'mul'):
raise ValueError('Bad mode: ' + newmode)
mode = newmode
if mode == 'add':
current += step
else:
current *= scale
# Test
gen = add_or_mul(1, 1, 2)
for i in range(5):
print(next(gen))
print(gen.send('mul'))
for i in range(4):
print(next(gen))
print(gen.send('add'))
for i in range(4):
print(next(gen))
输出
1
2
3
4
5
10
20
40
80
160
161
162
163
164
165
如果您在将此技术应用于图形遍历任务时遇到问题,请提出一个包含一些相关图形代码的新问题(可能链接到这个问题),这样回答者就不必为了测试和演示他们的代码。
关于python - "Double"迭代器和生成器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50100235/