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

时间:2017-10-28 23:47:20

标签: python function

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

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

可以作为:

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

4 个答案:

答案 0 :(得分:2)

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

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!")

用法:

>>> 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 :(得分:1)

def hello():
    print('Hello!')

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

警告:通常这不是一个好习惯,但这是做你要求的一种方式。

答案 2 :(得分:0)

可以,但 真的 不应该:这引起了大约一百零一个奇怪的担忧和潜在问题。但是,如果您坚持,实现将如下所示:

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()传递给它,您可以非常暂时获得您想要的界面。

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

答案 3 :(得分:0)

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)

用法:

  

请输入功能名称:foo1
  打电话给foo1

     

请输入功能名称:foo3
  没有名为this的函数