Python,SimPy:在函数内部使用yield

编程入门 行业动态 更新时间:2024-10-24 20:15:39
本文介绍了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

本文发布于:2023-11-23 13:49:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621658.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   Python   SimPy   yield

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!