如何在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"
答案 0 :(得分: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?的极好答案,以便更好地解释正在发生的事情。