【发布时间】: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