函数调用问题
各位大神,我在程序中定义了七个函数,想实现用随机函数来随机调用其中任意一个函数,如何实现?我采用的办法是把函数名保存在列表中,利用随机索引来调用函数,但是不行。 形参都一致吗 返回类型也是一致的吗 def fun1():pass
def fun2():
pass
def fun3():
pass
lst =
import random
random.choice(lst)() from random import choice
def fun1():
print('fun1')
def fun2():
print('fun2')
def fun3():
print('fun3')
def fun4():
print('fun4')
def fun5():
print('fun5')
def fun6():
print('fun6')
def fun7():
print('fun7')
fun_list = ['fun1', 'fun2', 'fun3', 'fun4', 'fun5', 'fun6', 'fun7']
def fun():
# 随机调用一个函数
exec(choice(fun_list) + "()")
fun() list=['image_I','image_L','image_J','image_O','image_S','image_T','image_Z']
list+'()'
这种方式也是可以的啦? wuyoujiao 发表于 2019-12-17 08:13
list=['image_I','image_L','image_J','image_O','image_S','image_T','image_Z']
list
import random
defimage_I():
print('image_I')
defimage_L():
print('image_l')
defimage_J():
print('image_j')
defimage_O():
print('image_o')
defimage_S():
print('image_s')
defimage_T():
print('image_t')
defimage_Z():
print('image_z')
lst=['image_I','image_L','image_J','image_O','image_S','image_T','image_Z']
eval(random.choice(lst)+'()')
eval(lst+'()')
'''
e:\pytest>python ex23.py
image_t
image_s
e:\pytest>python ex23.py
image_z
image_l
e:\pytest>python ex23.py
image_o
image_t
e:\pytest>python ex23.py
image_j
image_z
e:\pytest>python ex23.py
image_o
image_z
''' 看了各位的回复,查找了资料,才知道还有evel和exec 这样的好东西。谢谢 阿巴阿巴,其实我觉得设置一个随机数然后不同数字为条件设分支语句也可以?我真的是大新手
页:
[1]