Python成员函数装饰器使用实例作为参数
如何在python成员函数装饰器中使用实例作为参数。 下面是一个例子Python成员函数装饰器使用实例作为参数,python,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): pr
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"
不清楚您在寻找什么,但如果您希望能够使用对decorator内实例的引用:
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
要更好地解释发生了什么,请参阅的极好答案。您不能,因为在执行类块时,不仅实例还没有定义,类也没有定义。你想完成什么,使你认为你需要这样做?此外,你的foo装饰没有设置为接受参数。是否只想在foo decorator函数中引用实例
wrap
的参数s
将绑定到实例,您应将其传递到func
,如func
中所示。