Python,SimPy:在函数内部使用yield [英] Python, SimPy: Using yield inside functions

查看:251
本文介绍了Python,SimPy:在函数内部使用yield的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Helo, I'm building a relatively complex Discrete Event Simulation Model in SimPy.

当我尝试将yield语句放入函数中时,我的程序似乎无法正常工作.下面显示了一个示例.

When I try to put my yield statements inside functions, my program doesn't seem to work. Below shows an example.

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)

我从运行此命令得到的输出是:

The output I get from running this is:

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

holdLong()和holdShort方法似乎根本不起作用.我怎样才能解决这个问题?预先感谢.

The holdLong() and holdShort methods didn't seem to work at all. How can I fix this? Thanks in advance.

推荐答案

调用生成器函数将返回可以迭代的生成器对象.您只是忽略了此返回值,因此什么也没有发生.相反,您应该遍历生成器并重新产生所有值:

Calling a generator function returns a generator object that can be iterated over. You are simply ignoring this return value, so nothing happens. Instead, you should iterate over the generator and re-yield all values:

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,SimPy:在函数内部使用yield的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆