python代码:参数为一个指定的函数
这段代码很精炼,以后coding时可以效仿着写。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:
@file:testit.py
@time:2022-03-14 22:31
"""
# 书《Python核心编程(第二版).pdf》,作者:Wesley J. Chun
# 例11.5 测试函数(testit.py)
# testit()用其参数地调用了一个给定的函数,成功的话,返回一个和那函数返回值打包的True的返回值,或者False和失败的原因。
def testit(func, *nkwargs, **kwargs):
try:
retval = func(*nkwargs, **kwargs)
result = (True, retval)
except Exception as diag:
result = (False, str(diag))
return result
def test():
funcs = (int, float)
vals = (1234, 12.34, '1234', '12.34')
for eachFunc in funcs:
print('_' * 20)
for eachVal in vals:
retval = testit(eachFunc, eachVal)
if retval[0]:
print('%s = (%s) ' % ((eachFunc.__name__, eachVal), retval[1]))
else:
print('%s = FAILED, %s.' % ((eachFunc.__name__, eachVal), retval[1]))
if __name__ == '__main__':
test()
输出结果:
____________________ ('int', 1234) = (1234)? ('int', 12.34) = (12)? ('int', '1234') = (1234)? ('int', '12.34') = ?FAILED, invalid literal for int() with base 10: '12.34'. ____________________ ('float', 1234) = (1234.0)? ('float', 12.34) = (12.34)? ('float', '1234') = (1234.0)? ('float', '12.34') = (12.34)?
Process finished with exit code 0 ?
|