你可以創建一個類,將看到類方法和變量內部裝飾?創建裝飾,可以看到當前類方法
的裝飾在這裏看到犯規:self.longcondition()
class Foo:
def __init__(self, name):
self.name = name
# decorator that will see the self.longcondition ???
class canRun(object):
def __init__(self, f):
self.f = f
def __call__(self, *args):
if self.longcondition(): # <-------- ???
self.f(*args)
# this is supposed to be a very long condition :)
def longcondition(self):
return isinstance(self.name, str)
@canRun # <------
def run(self, times):
for i in xrange(times):
print "%s. run... %s" % (i, self.name)
這不工作,也沒有理由認爲它應該。你想要一個描述符。看到我的答案。 – aaronasterling 2010-09-13 21:42:03
@aaronasterling,你是對的。我基於以前使用functools.wraps的經驗回答了這個問題,但沒有經過測試,看看它是否有效。我已更新我的答案以使用它 – 2010-09-13 22:38:41