gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:35:09 33 4
gpt4 key购买 nike

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

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

最佳答案

诀窍是使用 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'

结果:

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

关于python - 如何在 Python 中使用变量作为函数名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34794634/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com