2013-02-07 30 views
2

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

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" 
+2

您不能这样做,因为不仅在实例中,而且在类类正在执行时尚未定义类。你试图完成什么,使你认为你需要这样做? – BrenBarn

+1

此外,你的foo装饰器没有设置参数。你只是想在你的foo装饰器函数中引用实例吗? 'wrap'的参数's'将被绑定到实例,你应该像'func''一样将它传递给'func'。 – Thomas

回答

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时,您仍然需要明确的自我。

请参阅How to make a chain of function decorators?的了不起的答案,以更好地解释发生了什么事。