为了账号安全,请及时绑定邮箱和手机立即绑定

通过遍历函数名称列表并将它们设为变量,从模块中调用许多 python 函数

通过遍历函数名称列表并将它们设为变量,从模块中调用许多 python 函数

凤凰求蛊 2023-03-30 17:29:16
我在 tld_list.py 中有三个类似的函数。我正在处理 mainBase.py 文件。我正在尝试创建一个变量字符串,它将通过遍历所有函数的列表来调用适当的函数。我的代码从函数名称列表中读取,遍历列表并在每次迭代时运行该函数。每个函数从不同的网站返回 10 条信息我已经尝试了 2 种变体,在下面注释为选项 A 和选项 B# This is mainBase.pyimport tld_list           # I use this in conjunction with Option Afrom tld_list import *    # I use this with Option BfunctionList = ["functionA", "functionB", "functionC"]tldIterator = 0while tldIterator < len(functionList):    # This will determine which function is called first    # In the first case, the function is functionA    currentFunction = str(functionList[tldIterator])选项A    currentFunction = "tld_list." + currentFunction    websiteName = currentFunction(x, y)    print(websiteName[1]    print(websiteName[2]    ...    print(websiteName[10]    选项B    websiteName = currentFunction(x, y)    print(websiteName[1]    print(websiteName[2]    ...    print(websiteName[10]即使看不到它,我也会通过结束每个循环来继续循环迭代tldIterator += 1由于相同的原因,这两个选项都失败了TypeError: 'str' object is not callable我想知道我做错了什么,或者是否有可能在循环中使用变量调用函数
查看完整描述

3 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

你有函数名,但你真正想要的是绑定到tld_list. 由于函数名称是模块的属性,因此getattr可以完成工作。此外,似乎列表迭代而不是跟踪您自己的tldIterator索引就足够了。


import tld_list


function_names = ["functionA", "functionB", "functionC"]

functions = [getattr(tld_list, name) for name in function_names]

for fctn in functions:

    website_name = fctn(x,y)


查看完整回答
反对 回复 2023-03-30
?
慕森王

TA贡献1777条经验 获得超3个赞

您可以创建一个字典来提供函数转换的名称:


def funcA(...): pass

def funcB(...): pass

def funcC(...): pass


func_find = {"Huey": funcA, "Dewey": funcB, "Louie": FuncC}

然后你可以打电话给他们,例如


result = func_find["Huey"](...)


查看完整回答
反对 回复 2023-03-30
?
MYYA

TA贡献1868条经验 获得超4个赞

你应该避免这种类型的代码。尝试使用 if 或引用代替。但你可以试试:

websiteName = exec('{}(x, y)'.format(currentFunction))


查看完整回答
反对 回复 2023-03-30
  • 3 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信