2017-10-28 90 views
0

例如,我想我的代码是:你可以将一个函数命名为用户输入吗?

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 
+2

有很多方法可以做到这一点,但是他们都尖叫着“CODE SMELL!”。 –

+3

在gods的名字为什么你会想要这样做 – 0TTT0

+0

否则,你可以调用特定的功能为特定的用户输入 –

回答

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

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

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

+1

这是一个解决方案,但应避免使用'''不惜任何代价eval''',因为它会导致不必要的代码执行。 – chowmean

+0

@chowmean,我同意。这就是为什么我加了我的警告。 –

+0

是的只是增加了解决方案和eval可以导致什么。谢谢:) – chowmean

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! 
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外壳,如果导入包含此功能(在我的情况,sandbox.py)文件,并通过globals()locals()它,你可以暂时得到你想要的接口。

>>> from sandbox import * 
>>> define_function(globals()) 
Enter a name for the function: hello 
>>> hello() 
Blah blah blah. 
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
没有名为此

功能
相关问题