首页 > 解决方案 > 有没有办法使用用户输入来调用函数?

问题描述

我知道字符串是不可调用的,但是能够使用这样的代码会很好。

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

标签: python

解决方案


有几种方法:

最直接的一种,在字典中收集所有符合条件的函数:

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

推荐阅读