猿问

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

我在 tld_list.py 中有三个类似的函数。我正在处理 mainBase.py 文件。


我正在尝试创建一个变量字符串,它将通过遍历所有函数的列表来调用适当的函数。我的代码从函数名称列表中读取,遍历列表并在每次迭代时运行该函数。每个函数从不同的网站返回 10 条信息


我已经尝试了 2 种变体,在下面注释为选项 A 和选项 B


# This is mainBase.py


import tld_list           # I use this in conjunction with Option A

from tld_list import *    # I use this with Option B


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

tldIterator = 0

while 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


我想知道我做错了什么,或者是否有可能在循环中使用变量调用函数


凤凰求蛊
浏览 172回答 3
3回答

紫衣仙女

你有函数名,但你真正想要的是绑定到tld_list. 由于函数名称是模块的属性,因此getattr可以完成工作。此外,似乎列表迭代而不是跟踪您自己的tldIterator索引就足够了。import tld_listfunction_names = ["functionA", "functionB", "functionC"]functions = [getattr(tld_list, name) for name in function_names]for fctn in functions:&nbsp; &nbsp; website_name = fctn(x,y)

慕森王

您可以创建一个字典来提供函数转换的名称:def funcA(...): passdef funcB(...): passdef funcC(...): passfunc_find = {"Huey": funcA, "Dewey": funcB, "Louie": FuncC}然后你可以打电话给他们,例如result = func_find["Huey"](...)

MYYA

你应该避免这种类型的代码。尝试使用 if 或引用代替。但你可以试试:websiteName&nbsp;=&nbsp;exec('{}(x,&nbsp;y)'.format(currentFunction))
随时随地看视频慕课网APP

相关分类

Python
我要回答