|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import time
def time_master(func):
print('开始运行程序')
start = time.time()
func()
stop = time.time()
print('结束程序运行')
print(f'一共耗费了{(stop-start):.2f}秒。')
def myfunc():
time.sleep(2)
print('hello')
a=time_master(myfunc)
a()
开始运行程序
hello
结束程序运行
一共耗费了2.01秒。
Traceback (most recent call last):
File "D:/BaiduNetdiskDownload/python/函数6-测试(自己做).py", line 16, in <module>
a()
TypeError: 'NoneType' object is not callable
请教大神,这里的代码运行了但是最后报错,代码哪里有问题啊
代码中的问题是您试图调用一个NoneType对象。这是因为time_master函数没有返回一个函数,而您试图将其返回值作为函数调用。实际上,您已经在time_master函数内部调用了func()。请参考以下修改后的代码:
- import time
- def time_master(func):
- def wrapper():
- print('开始运行程序')
- start = time.time()
- func()
- stop = time.time()
- print('结束程序运行')
- print(f'一共耗费了{(stop-start):.2f}秒。')
- return wrapper
- def myfunc():
- time.sleep(2)
- print('hello')
- a = time_master(myfunc)
- a()
复制代码
这里,我们将time_master函数修改为一个装饰器,它返回一个名为wrapper的内部函数。然后,我们将myfunc作为参数传递给time_master,并将返回的wrapper函数赋值给变量a。最后,我们调用a(),这将执行wrapper函数并间接地调用myfunc。
|
|