鱼C论坛

 找回密码
 立即注册
查看: 1273|回复: 7

函数调用问题

[复制链接]
发表于 2019-12-16 16:19:22 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
各位大神,我在程序中定义了七个函数,想实现用随机函数来随机调用其中任意一个函数,如何实现?我采用的办法是把函数名保存在列表中,利用随机索引来调用函数,但是不行。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-12-16 16:25:46 | 显示全部楼层
形参都一致吗 返回类型也是一致的吗
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-12-16 16:27:31 | 显示全部楼层
  1. def fun1():
  2.     pass

  3. def fun2():
  4.     pass

  5. def fun3():
  6.     pass

  7. lst = [fun1, fun2, fun3]
  8. import random
  9. random.choice(lst)()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-12-16 18:47:03 | 显示全部楼层
  1. from random import choice


  2. def fun1():
  3.     print('fun1')


  4. def fun2():
  5.     print('fun2')


  6. def fun3():
  7.     print('fun3')


  8. def fun4():
  9.     print('fun4')


  10. def fun5():
  11.     print('fun5')


  12. def fun6():
  13.     print('fun6')


  14. def fun7():
  15.     print('fun7')


  16. fun_list = ['fun1', 'fun2', 'fun3', 'fun4', 'fun5', 'fun6', 'fun7']


  17. def fun():
  18.     # 随机调用一个函数
  19.     exec(choice(fun_list) + "()")


  20. fun()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-12-17 08:13:44 | 显示全部楼层
list=['image_I','image_L','image_J','image_O','image_S','image_T','image_Z']
list[random.randint(0,6)]+'()'
这种方式也是可以的啦?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 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[random.randint(0, ...
  1. import random
  2.    
  3. def  image_I():
  4.    print('image_I')
  5.    
  6. def  image_L():
  7.    print('image_l')
  8.    
  9. def  image_J():
  10.    print('image_j')   

  11. def  image_O():
  12.    print('image_o')

  13. def  image_S():
  14.    print('image_s')

  15. def  image_T():
  16.    print('image_t')

  17. def  image_Z():
  18.    print('image_z')   
  19.    
  20. lst=['image_I','image_L','image_J','image_O','image_S','image_T','image_Z']
  21. eval(random.choice(lst)+'()')
  22. eval(lst[random.randint(0,6)]+'()')

  23. '''
  24. e:\pytest>python ex23.py
  25. image_t
  26. image_s

  27. e:\pytest>python ex23.py
  28. image_z
  29. image_l

  30. e:\pytest>python ex23.py
  31. image_o
  32. image_t

  33. e:\pytest>python ex23.py
  34. image_j
  35. image_z

  36. e:\pytest>python ex23.py
  37. image_o
  38. image_z

  39. '''
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-12-18 07:58:52 | 显示全部楼层
看了各位的回复,查找了资料,才知道还有evel和exec 这样的好东西。谢谢
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-1-1 00:55:08 | 显示全部楼层
阿巴阿巴,其实我觉得设置一个随机数然后不同数字为条件设分支语句也可以?我真的是大新手
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-30 15:36

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表