Python,SimPy:在函数内使用yield

1 投票
2 回答
2075 浏览
提问于 2025-04-17 07:14

你好,我正在用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这两个方法似乎根本没有起作用。我该怎么解决这个问题呢?提前谢谢你。

2 个回答

1

在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
6

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

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

撰写回答