【问题标题】:Python, SimPy: Using yield inside functionsPython,SimPy:在函数内部使用 yield
【发布时间】:2012-01-07 23:22:37
【问题描述】:

Helo,我正在 SimPy 中构建一个相对复杂的离散事件模拟模型。

当我尝试将 yield 语句放在函数中时,我的程序似乎无法运行。下面是一个例子。

import SimPy.SimulationTrace as Sim
import random

## Model components ##
class Customer(Sim.Process):
    def visit(self):
        yield Sim.hold, self, 2.0
        if random.random()<0.5:
            self.holdLong()
        else:
            self.holdShort()

    def holdLong(self):
        yield Sim.hold, self, 1.0
        # more yeild statements to follow

    def holdShort(self):
        yield Sim.hold, self, 0.5
        # more yeild statements to follow

## Experiment data ##
maxTime = 10.0 #minutes

## Model/Experiment ##
#random.seed(12345)
Sim.initialize()
c = Customer(name = "Klaus") #customer object
Sim.activate(c, c.visit(), at = 1.0)
Sim.simulate(until=maxTime)

我运行这个得到的输出是:

0 activate <Klaus > at time: 1.0 prior: False
1.0 hold  < Klaus >  delay: 2.0
3.0 <Klaus > terminated

holdLong() 和 holdShort 方法似乎根本不起作用。我怎样才能解决这个问题?提前致谢。

【问题讨论】:

    标签: python simulation simpy


    【解决方案1】:

    调用生成器函数会返回一个可以迭代的生成器对象。你只是忽略了这个返回值,所以什么也没有发生。相反,您应该遍历生成器并重新生成所有值:

    class Customer(Sim.Process):
        def visit(self):
            yield Sim.hold, self, 2.0
            if random.random()<0.5:
                for x in self.holdLong():
                    yield x
            else:
                for x in self.holdShort():
                    yield x
    

    【讨论】:

    • 我相信 Python 3.3 的新 'yield from' 语法在这里会很有用。
    【解决方案2】:

    在 Python 中,yield 不能通过函数调用向上传播。将visit 更改为如下内容:

    def visit(self):
        yield Sim.hold, self, 2.0
        if random.random()<0.5:
            for x in self.holdLong():
                yield x
        else:
            for x in self.holdShort():
                yield x
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-16
      • 1970-01-01
      • 2015-12-03
      • 2016-05-04
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      相关资源
      最近更新 更多