[英]How to pass function name as String in Python 3
我正在测试一堆函数,并希望获得我测试的函数的名称以打印到控制台。
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]))
当我执行上述操作时,而不是函数名称,我得到了:
真的过去了
每次迭代。 我哪里做错了?
首先,让你的列表保存函数对象(这意味着你不应该调用它们,因为如果你这样做,你最终会持有返回值 )。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.