【发布时间】:2013-11-19 15:20:23
【问题描述】:
我想听听您对设计的建议。我有一个控制温度的烤箱,我正在做一些与温度相关的测量。我基本上是在设置温度,测量一些东西然后继续前进。
我想出了两个设计,当然是简化的,如下所示。第一个使用基于回调的方法:
class Oven(object):
# ... some methods
def step_temperature(start, stop, num, rate, callback):
temperatures = np.linspace(start, stop, num)
for t in temperatures:
self.temperature = t, rate # sweep to temperature with given rate
self._wait_for_stability() # wait until temperature is reached.
callback(t) # execute the measurement
# Use Case
oven = Oven()
oven.step_temperature(start=20, stop=200, num=10, rate=1, callback=measure_stuff)
第二种设计是基于生成器的设计
class Oven(object):
# ... some methods
def step_temperature(start, stop, num, rate):
temperatures = np.linspace(start, stop, num)
for t in temperatures:
self.temperature = t, rate
self._wait_for_stability()
yield t
# Use Case
oven = Oven()
for t in oven.step_temperature(start=20, stop=200, num=10, rate=1):
measure_stuff(t)
我倾向于第二种设计,但我对您的建议很感兴趣。如果有更好的方法,请随时告诉我。
【问题讨论】:
-
这两个实现有很多不同的属性。第一个是“阻塞”,而第二个允许停止和恢复计算(这可能是也可能不是你想要的)。如果您总是在
for x in the_generator(): callback(x)中使用它,那么我认为没有理由使用生成器,只需在方法中调用callback。 -
生成器很适合实现花哨的算法。但是为了自动化一些测量,这通常是一些基于时间的过程,我会坚持标准的过程代码,所以我的投票是第一个解决方案。
标签: python callback generator class-design coroutine