Python。有没有办法随机挑选一个def?

2024-05-20 21:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在def函数中存储每个Callout 例如:

def shooting():
    print("bang bang")

def mugging():
    print("money, now!")
callout = ['shooting', 'mugging']
randomthing = random.choice(callout)
print(randomthing + "()")

因此,每个callout都存储在def函数中。然后在callout和randomthing中随机化。然后(我知道这部分是错误的)我希望它调用mugging()或shooing(),但有50/50的机会。你知道吗


Tags: 函数def错误randomnowprintbangchoice
1条回答
网友
1楼 · 发布于 2024-05-20 21:24:04

你差点就成功了!只需删除引号,并直接存储函数名。Python中的函数与变量类似:

callout = [shooting, mugging]
randomthing = random.choice(callout)
print(randomthing())

相关问题 更多 >