我想写一个具有以下接口的类。
class Automaton:
""" A simple automaton class """
def iterate(self, something):
""" yield something and expects some result in return """
print("Yielding", something)
result = yield something
print("Got \"" + result + "\" in return")
return result
def start(self, somefunction):
""" start the iteration process """
yield from somefunction(self.iterate)
raise StopIteration("I'm done!")
def first(iterate):
while iterate("what do I do?") != "over":
continue
def second(iterate):
value = yield from iterate("what do I do?")
while value != "over":
value = yield from iterate("what do I do?")
# A simple driving process
automaton = Automaton()
#generator = automaton.start(first) # This one hangs
generator = automaton.start(second) # This one runs smoothly
next_yield = generator.__next__()
for step in range(4):
next_yield = generator.send("Continue...({})".format(step))
try:
end = generator.send("over")
except StopIteration as excp:
print(excp)
这个想法是 Automaton 将定期向调用者产生值,调用者反过来将结果/命令发送回 Automaton。
问题是决策过程“somefunction”将是一些我无法控制的用户定义函数。这意味着我真的不能指望它会yield from
在前面调用 iterate 方法。最糟糕的是,用户可能想要在这个 Automaton 类中插入一些他无法控制的第三方功能。这意味着用户可能无法重写他somefunction
的内容以将其包含yield from
在iterate
调用前。
需要明确的是:我完全理解为什么使用该first
功能会挂起自动机。我只是想知道是否有办法改变iterate
或start
使first
函数工作的定义。