【问题标题】:Can you name a function as a user input?您可以将函数命名为用户输入吗?
【发布时间】:2018-04-10 06:31:42
【问题描述】:

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

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

【问题讨论】:

  • 有很多方法可以做到,但所有方法都在尖叫“CODE SMELL!”。
  • 否则你可以为特定的用户输入调用特定的函数
  • 这是一个如果你不得不问,你不应该这样做的时候。可以做到,但几乎从来没有一个好主意。您要解决的更大问题是什么?
  • 那么我就告诉你我需要它做什么:我在 python 中制作了一个不和谐的机器人,如果我想制作一个自定义命令命令,我必须让用户能够命名该函数

标签: python function


【解决方案1】:
def hello():
    print('Hello!')

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

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

【讨论】:

  • 这是一种解决方案,但您应该不惜一切代价避免使用eval,因为它可能导致不必要的代码执行。
  • @chowmean,我同意。这就是我添加警告的原因。
  • 是的,只是添加到解决方案中以及 eval 会导致什么。谢谢:)
  • 我不确定这是否能回答问题。您将函数名称硬编码为hello(),但他希望将其命名为无论用户键入什么
  • globals()[fn_name]() 可以让这更安全。
【解决方案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!

【讨论】:

    【解决方案3】:

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

    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.
    

    【讨论】:

      【解决方案4】:
      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
      没有这个函数

      【讨论】:

        猜你喜欢
        • 2018-07-16
        • 1970-01-01
        • 1970-01-01
        • 2015-12-01
        • 1970-01-01
        • 2014-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多