蟒蛇.有没有办法选择随机def?

T.p*_*.ps 2 python random function

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

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

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

所以每个标注都存储在def函数中.然后它在callout和randomthing中随机化.然后(我知道这部分是错的)我希望它可以调用mugging()或者shooing()但是有50/50的机会.

Bur*_*lid 6

你几乎拥有它!只需删除引号,直接存储函数名称即可.Python中的函数就像变量一样:

callout = [shooting, mugging]
randomthing = random.choice(callout)
print(randomthing())
Run Code Online (Sandbox Code Playgroud)