qq_25894535 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日

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?