【问题标题】:Decorators with access to original function可以访问原始功能的装饰器
【发布时间】:2012-12-21 01:24:38
【问题描述】:

我定义了以下装饰器:

def loop_callback(func):
    """Only works in programs with a single main loop. Can call .sameThread
    to access the original unwrapped function directly"""
    @wraps(func)
    def wrapped_func(*args, **varargs):
        if mainThread==threading.current_thread():
            print("We are in the loop thread")
            func(*args, **varargs)
        else:
            print("In another thread")
            loop.add_callback(lambda: func(*args, **varargs))
    wrapped_func.orig=func
    return wrapped_func

这个想法是你应该能够通过调用myObject.myFunction.orig(arg1, arg2) 之类的东西来访问原始函数。不幸的是,orig 不会收到 self 对象,只有 arg1arg2。有什么办法可以解决这个问题,以便可以按照我想要的方式调用它?

【问题讨论】:

    标签: python decorator


    【解决方案1】:

    您也许可以弄清楚如何将它硬塞到这样的装饰器中,以便在您正在谈论的场景中最终得到您想要的绑定方法,但实际上,这可能是一个很好的机会你来了解descriptor protocol

    【讨论】:

      猜你喜欢
      • 2013-02-03
      • 2016-11-24
      • 1970-01-01
      • 2018-02-01
      • 2020-12-10
      • 2014-12-15
      • 1970-01-01
      • 2013-01-15
      • 2013-09-12
      相关资源
      最近更新 更多