自定义装饰器运行报错
装饰器实现的是检测其他线程代码超时的功能但是定义两层不知道该返回什么就会报错 三层就没问题,求解答
正常执行代码:
import threading
import time
def watchdog(thread, timeout):
time.sleep(timeout)
if thread.is_alive():
print("Thread timed out")
# Terminate the thread
thread.stop = True
def watchdog_decorator(timeout):
def decorator(func):
def wrapper(*args, **kwargs):
thread = threading.Thread(target=func,args=args,kwargs=kwargs)
thread.start()
watchdog_thread = threading.Thread(target=watchdog, args=(thread, timeout))
watchdog_thread.start()
thread.join()
print("Main thread finished")
return wrapper
return decorator
@watchdog_decorator(3)
def test():
time.sleep(10)
if __name__ == "__main__":
test()
报错代码:
import threading
import time
def watchdog(thread, timeout):
time.sleep(timeout)
if thread.is_alive():
print("Thread timed out")
# Terminate the thread
thread.stop = True
def watchdog_decorator(timeout):
def decorator(func):
thread = threading.Thread(target=func)
thread.start()
watchdog_thread = threading.Thread(target=watchdog, args=(thread, timeout))
watchdog_thread.start()
thread.join()
print("Main thread finished")
return decorator
@watchdog_decorator(3)
def test():
time.sleep(10)
if __name__ == "__main__":
test()
第二段代码在不增加装饰器里的函数的情况下该怎样更改才能使代码不会报错呢 decorator函数应该返回什么
你这种情况只能用三层,装饰器接收一个函数返回一个函数,你的func参数是传给了decorator()。
事实上,decorator才是装饰器的外函数,内部还需要一个内函数。
watchdog_decorator只是你在装饰器外层给装饰器加了一个参数timeout。
闭包的重点:
1.外函数的内部定义了一个内函数
2.内部函数使用了外部函数的临时变量
3.外函数的返回值是内函数的引用
参考:Python装饰器的实现和万能装饰器
回答不易,求求您采纳点赞哦 感激不尽
报错代码中的问题是decorator函数没有返回一个wrapper函数,需要在decorator函数中增加一个return wrapper语句:
def watchdog_decorator(timeout):
def decorator(func):
def wrapper(*args, **kwargs):
thread = threading.Thread(target=func,args=args,kwargs=kwargs)
thread.start()
watchdog_thread = threading.Thread(target=watchdog, args=(thread, timeout))
watchdog_thread.start()
thread.join()
print("Main thread finished")
return wrapper
return wrapper