如何在 Python 中使用变量作为函数名

新手上路,请多包涵

是否可以在 python 中使用变量作为函数名?例如:

 list = [one, two, three]
for item in list:
    def item():
         some_stuff()

原文由 thecatwagon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 963
1 个回答

诀窍是使用 globals():

 globals()['use_variable_as_function_name']()

将相当于

use_variable_as_function_name()

发现于:George Sakkis https://bytes.com/topic/python/answers/792283-calling-variable-function-name


以下是我现在需要的上述问题的有用应用(这就是我来这里的原因):根据 URL 的性质将特殊功能应用于 URL:

 l = ['condition1', 'condition2', 'condition3']

我曾经写过

if 'condition1.' in href:
    return do_something_condition1()
if 'condition2.' in href:
    return do_something_condition2()
if 'condition3.' in href:
    return do_something_condition3()

等等——我的名单现在有 19 个成员,并且还在不断增加。

在调查主题和开发过程中,函数代码已经很自然地成为主函数的一部分,这使得阅读起来很快变得很糟糕,因此将工作代码重新定位到函数中已经是一种极大的解脱。

上面这段笨拙的代码可以替换为:

 for e in l:              # this is my condition list
    if e + '.' in href:  # this is the mechanism to choose the right function
        return globals()['do_something_' + e]()

这样,无论条件列表可能增长多长,主要代码都保持简单易读。

那些对应于条件标签的函数必须按照惯例声明,当然,这取决于所讨论的 URL 类型的性质:

 def do_something_condition1(href):
    # special code 1
    print('========1=======' + href)

def do_something_condition2(href):
    # special code 2
    print('========2=======' + href)

def do_something_condition3(href):
    # special code 3
    print('========3=======' + href)

测试:

 >>> href = 'https://google.com'
>>> for e in l:
...     globals()['do_something_' + e](href)
...
========1=======https://google.com
========2=======https://google.com
========3=======https://google.com

或者,将其建模为更接近上述场景:

 success = '________processed successfully___________ '

def do_something_google(href):
    # special code 1
    print('========we do google-specific stuff=======')
    return success + href

def do_something_bing(href):
    # special code 2
    print('========we do bing-specific stuff=======')
    return success + href

def do_something_wikipedia(href):
    # special code 3
    print('========we do wikipedia-specific stuff=======')
    return success + href

测试:

 l = ['google', 'bing', 'wikipedia']

href = 'https://google.com'

def test(href):
    for e in l:
        if e + '.' in href:
            return globals()['do_something_' + e](href)

>>> test(href)
========we do google-specific stuff=======
'________processed successfully___________ https://google.com'

结果:

现在对该问题的进一步阐述只是将条件列表逐一扩充并根据参数编写相应的函数。此后,上述机制将选择正确的一个。

原文由 kklepper 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题