擅长:python、mysql、java
<p>您可以使用<code>yield</code>关键字来创建co例程。以下是一个例子:</p>
<pre><code>import random
random.seed()
def do_action1():
print("Hello")
yield
print("HELLO!")
yield
print("hello?")
def do_action2():
print("Are you there?")
yield
print("ARE YOU THERE!")
yield
print("I'm scared.")
def do_action3():
print("Is somebody out there?")
yield
print("SOMEBODY IS OUT THERE!")
yield
print("I'm dead.")
def bot(*actions):
actions = [action() for action in actions]
while actions:
action = random.choice(actions)
try:
next(action)
except StopIteration:
actions.remove(action)
return
bot(do_action1, do_action2, do_action3)
</code></pre>