python - 有没有办法使用用户输入来调用函数?
问题描述
我知道字符串是不可调用的,但是能够使用这样的代码会很好。
def test1():
print('7')
def test2():
print('7')
def test3():
print('7')
def test4():
print('7')
def test5():
print('7')
i = input(">") #assume the input is one of the function names
i()
解决方案
有几种方法:
最直接的一种,在字典中收集所有符合条件的函数:
functions = {f.__name__: f for f in [test1, test2, test3, test4, test5, test6]}
functions[input(">")]()
或者,一种偷偷摸摸的方式,使用globals()
,请注意您将有效地允许用户调用全局范围内的任何函数,而不仅仅是您认为他们应该拥有的函数:
globals()[input(">")]()
或者是一种超级偷偷摸摸的使用方式,eval()
或者如果你在一个循环中这样做,只需启动一个 shell 以允许使用 完全任意代码执行code.interact()
,这也将允许用户指定函数参数,如果用户帐户重新格式化你的硬盘运行代码有权这样做:
import code
code.interact()
推荐阅读
- android - 发现周期性
链:activity_maps_main 包括 activity_maps_main - python - 带有 read_csv 的嵌套 If 语句
- javascript - 用 .toLocaleString() 替换 ParseFloat(.ToFixed()) 以获得精确的金钱
- while-loop - 是否可以仅使用 1 个循环来循环 2 个值?
- java - 在创建新课程时,我应该如何将老师添加到新课程中?
- android - NavigationDrawer 未与 AndroidX 一起出现
- c - C中的简单if语句总是返回true
- amazon-web-services - 由弹性 beantalk 生成的 ec2 实例的默认用户名
- javascript - 如何计算每一行的值?
- angular - 如何将多个对象发布到spring-boot?