【问题标题】:Python member function decorators use instance as a parameterPython 成员函数装饰器使用实例作为参数
【发布时间】:2013-02-07 06:46:36
【问题描述】:

如何在python成员函数装饰器中使用instance作为参数。 下面是一个例子。

def foo(func):
    def wrap(s):
        func()
        s.ma()
    return wrap

class A:
    def ma(self):
        print "this is ma"

    @foo(self)     #error.name 'self' is not defined
    def mb(self):
        print "this is mb"

【问题讨论】:

  • 你不能,因为在执行类块时不仅实例而且类还没有定义。你想完成什么让你认为你需要这样做?
  • 此外,您的 foo 装饰器未设置为接受参数。您是否只想在 foo 装饰器函数中引用实例? wrap 的参数s 将绑定到实例,您应该将其传递给func,如func(s)

标签: python


【解决方案1】:

不清楚您在寻找什么,但如果您希望能够在装饰器中使用对实例的引用:

def foo(func):
    def wrap(s): # I'd call this 'self' instead of 's' to remind us it's a reference to an instance

        func(s) # This is a function, not a method yet - so we need to pass in the reference

        s.ma() # This is a method, because you use attribute lookup on the object s to get it
    return wrap

class A:
    def ma(self):
        print "this is ma"

    @foo     # if the way foo wraps mb doesn't depend on some arg, don't use args here
    def mb(self):
        print "this is mb"

我认为您在这里对 Python 中的方法和函数之间的区别感到困惑 - 您似乎期望 func 会像方法一样工作,而实际上它在被修饰时仍然是一个函数。在实例上查找属性时,装饰函数将被转换为方法;这意味着当您在包装函数中调用 func 时,您仍然需要显式 self。

请参阅How to make a chain of function decorators? 的精彩回答,以更好地解释正在发生的事情。

【讨论】:

    猜你喜欢
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 2013-01-25
    • 2020-07-11
    • 2011-03-23
    • 1970-01-01
    相关资源
    最近更新 更多