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: