关于python:你能将一个函数命名为用户输入吗?

Can you name a function as a user input?

例如,我希望我的代码是:

1
2
3
name_of_function = input("Please enter a name for the function:")
def name_of_function():
    print("blah blah blah")

其工作原理如下:

1
2
3
Please enter a name for the function: hello
>>>hello()
blah blah blah


我将使用包含对每个函数的引用的字典:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def func_one():
    print("hello")

def func_two():
    print("goodbye")

def rename_function(func_dict, orig_name, new_name):
    func_dict[new_name] = func_dict[orig_name]
    del func_dict[orig_name]

functions = {
   "placeholder_one": func_one,
   "placeholder_two": func_two
}

rename_function(
    functions,
   "placeholder_one",
    input("Enter new greeting function name:")
)

rename_function(
    functions,
   "placeholder_two",
    input("Enter new farewell function name:")
)

while True:
    func_name = input("Enter function to call:")
    if func_name in functions:
        functions[func_name]()
    else:
        print("That function doesn't exist!")

用途:

1
2
3
4
5
6
7
8
>>> Enter new greeting function name: hello
>>> Enter new farewell function name: goodbye
>>> Enter function to call: hello
hello
>>> Enter function to call: goodbye
goodbye
>>> Enter function to call: hi
That function doesn't exist!

1
2
3
4
5
def hello():
    print('Hello!')

fn_name = input('fn name: ') # input hello
eval(fn_name)() # this will call the hello function

警告:通常这不是一个好的实践,但这是一种做你要求的事情的方法。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Foo(object):
    def foo1(self):
        print ('call foo1')

    def foo2(self):
        print ('call foo2')

    def bar(self):
        print ('no function named this')


def run(func_name):
    funcs = Foo()
    try:
        func = getattr(funcs, func_name)
    except Exception as ex:
        funcs.bar()
        return
    func()


func_name = raw_input('please input a function name:')
run(func_name)

用途:

please input a function name:foo1
call foo1

please input a function name:foo3
no function named this


你可以,但你真的不应该:这引起了大约110个奇怪的问题和潜在的问题。但是,如果您坚持这样做,那么实现将如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
def define_function(scope):

    name_of_function = input("Enter a name for the function:")

    function_body ="""def {}():

                        print("Blah blah blah.")


                   """
.format(name_of_function)

    exec(function_body, scope)

在python shell中,如果导入包含此函数的文件(在我的例子中,是sandbox.py并将globals()locals()传递给它,则可以非常暂时地获得所需的接口。

1
2
3
4
5
>>> from sandbox import *
>>> define_function(globals())
Enter a name for the function: hello
>>> hello()
Blah blah blah.