wuyoujiao 发表于 2019-12-16 16:19:22

函数调用问题

各位大神,我在程序中定义了七个函数,想实现用随机函数来随机调用其中任意一个函数,如何实现?我采用的办法是把函数名保存在列表中,利用随机索引来调用函数,但是不行。

wp231957 发表于 2019-12-16 16:25:46

形参都一致吗 返回类型也是一致的吗

冬雪雪冬 发表于 2019-12-16 16:27:31

def fun1():
    pass

def fun2():
    pass

def fun3():
    pass

lst =
import random
random.choice(lst)()

zltzlt 发表于 2019-12-16 18:47:03

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()

wuyoujiao 发表于 2019-12-17 08:13:44

list=['image_I','image_L','image_J','image_O','image_S','image_T','image_Z']
list+'()'
这种方式也是可以的啦?

wp231957 发表于 2019-12-17 10:55:24

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

'''

wuyoujiao 发表于 2019-12-18 07:58:52

看了各位的回复,查找了资料,才知道还有evel和exec 这样的好东西。谢谢

啄眷鸟 发表于 2022-1-1 00:55:08

阿巴阿巴,其实我觉得设置一个随机数然后不同数字为条件设分支语句也可以?我真的是大新手
页: [1]
查看完整版本: 函数调用问题