Python, SimPy: Using yield inside functions

匿名 (未验证) 提交于 2019-12-03 01:36:02

问题:

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

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 

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

回答1:

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 


回答2:

In Python, yield can't propagate upward through a function call. Change visit to something like this:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!