如何在Python 3中将函数名称作为String传递

时间:2018-03-13 06:11:18

标签: python

我正在测试一堆函数,并且想要将我测试的函数的名称打印到控制台。

if __name__ == '__main__':
passedMsg = "%s passed"
failedMsg = "%s failed"

list_of_functions = [testaddDict(), testaddDictN(), testcharCount(), testcharCount2(), testlookupVal(),
                     testlookupVal2(), testfunRun(), testnumPaths(), testnumbersToSum(), teststreamSquares(),
                     teststreamSquares()]

for i in range(0, len(list_of_functions)):
    if list_of_functions[i]:
        print (passedMsg % str(list_of_functions[i]))
    else:
        print (failedMsg % str(list_of_functions[i]))

当我执行上述操作时,而不是函数名称,我得到了:

  

真实传递

每次迭代。我哪里做错了?

1 个答案:

答案 0 :(得分:3)

首先,让你的列表保存函数对象(这意味着你不应该调用它们,因为如果你这样做,你最终会持有返回值)。

list_of_functions = [testaddDict, testaddDictN, ...]

这是有效的,因为函数是python中的第一类对象(意味着您可以将它们分配给其他变量,依此类推)。接下来,修改你的循环,直接迭代list_of_functions

for f in list_of_functions:
    if f():
        print(passedMsg % f.__name__)
    else:
        print(failedMsg % f.__name__)

最重要的变化是您在if语句中调用该函数,并通过其返回值确定它是已通过还是失败。相应地打印f.__name__,其中__name__属性包含函数的“名称”。

为什么我建议直接迭代函数列表(而不是range),主要是为了提高效率和简单性。

这是一个包含两个功能的演示:

def f1():
    return True

def f2():
    return False

for f in [f1, f2]:
    if f():
        print(passedMsg % f.__name__)
    else:
        print(failedMsg % f.__name__)

f1 passed
f2 failed