带参数的Python装饰器与访问类实例
我有一个类,定义如下:
class SomeViewController(BaseViewController):
@requires('id', 'param1', 'param2')
@ajaxGet
def create(self):
#do something here
有没有可能写一个装饰器函数,它可以:
- 接收一组参数(args),可能还有一些关键字参数(kwargs),并且
- 访问定义了这个方法的类的实例?
比如对于这个 @ajaxGet 装饰器,self
里面有一个叫 type
的属性,里面存着我需要检查的值。
谢谢
1 个回答
19
是的。实际上,从你提到的意思来看,似乎没有办法写一个不访问 self
的装饰器。被装饰的函数会包裹原始函数,所以它必须至少接受原始函数所接受的参数(或者一些可以从中推导出的参数),否则就无法把正确的参数传递给底层的函数。
你不需要做什么特别的事情,只需写一个普通的装饰器:
def deco(func):
def wrapper(self, *args, **kwargs):
print "I am the decorator, I know that self is", self, "and I can do whatever I want with it!"
print "I also got other args:", args, kwargs
func(self)
return wrapper
class Foo(object):
@deco
def meth(self):
print "I am the method, my self is", self
然后你就可以直接使用它了:
>>> f = Foo()
>>> f.meth()
I am the decorator, I know that self is <__main__.Foo object at 0x0000000002BCBE80> and I can do whatever I want with it!
I also got other args: () {}
I am the method, my self is <__main__.Foo object at 0x0000000002BCBE80>
>>> f.meth('blah', stuff='crud')
I am the decorator, I know that self is <__main__.Foo object at 0x0000000002BCBE80> and I can do whatever I want with it!
I also got other args: (u'blah',) {'stuff': u'crud'}
I am the method, my self is <__main__.Foo object at 0x0000000002BCBE80>