lyitcc 2023-02-12 00:26 采纳率: 85.7%
浏览 17
已结题

python 自定义装饰器运行报错

自定义装饰器运行报错
装饰器实现的是检测其他线程代码超时的功能但是定义两层不知道该返回什么就会报错 三层就没问题,求解答
正常执行代码:

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函数应该返回什么

  • 写回答

3条回答 默认 最新

  • 小斌哥ge 优质创作者: python技术领域 2023-02-12 10:32
    关注

    你这种情况只能用三层,装饰器接收一个函数返回一个函数,你的func参数是传给了decorator()。
    事实上,decorator才是装饰器的外函数,内部还需要一个内函数。
    watchdog_decorator只是你在装饰器外层给装饰器加了一个参数timeout。
    闭包的重点:
    1.外函数的内部定义了一个内函数
    2.内部函数使用了外部函数的临时变量
    3.外函数的返回值是内函数的引用
    参考:Python装饰器的实现和万能装饰器

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 2月21日
  • 已采纳回答 2月13日
  • 创建了问题 2月12日