如何在装饰器中的decorator中调用实例属性。以下是我的测试代码:
#!/usr/bin/env python
# coding=utf-8
class Foo(object):
""""""
def __init__(self):
""""""
self.a = 1
def decorator(func):
def wrapper(*args, **kw):
""""""
print self.a # or do something with self.a
self.a += 1
return wrapper
@decorator
def call_decorator(self):
""""""
pass
和
In [1]: import foo
In [2]: f = foo.Foo()
In [3]: f.call_decorator
Out[3]: <bound method Foo.wrapper of <foo.Foo object at 0x7fcc72c6a710>>
In [4]: f.call_decorator()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-70d92b784c01> in <module>()
----> 1 f.call_decorator()
/home/fit/log/1228/foo.py in wrapper(*args, **kw)
11 def wrapper(*args, **kw):
12 """"""
---> 13 print self.a
14 return wrapper
15
NameError: global name 'self' is not defined
In [5]:
如果我在self
中添加def decorator(self, func):
,并且@decorator
中会出现错误,则需要2个参数。装饰师不容易理解。
所以,我只想在装饰器中使用实例a
的属性f
,我该怎么做?
答案 0 :(得分:1)
wrapper
在任何其他函数的参数中收到self
的{{1}},而不是decorator
,所以定义应该是这样的:
def decorator(func):
@functools.wraps(func) # a good thing to do
def wrapper(self, *args, **kw):
print self.a # or do something with self.a
self.a += 1
# if you need to call it, otherwise what's the point of the decorator:
return func(self, *args, **kw)
return wrapper