问题
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
来源:https://stackoverflow.com/questions/8296892/python-simpy-using-yield-inside-functions