带有参数和访问类实例的Python Decorator

时间:2013-03-04 06:28:14

标签: python python-2.7 decorator

我的课程定义如下:

class SomeViewController(BaseViewController):
    @requires('id', 'param1', 'param2')
    @ajaxGet
    def create(self):
        #do something here

是否可以编写一个装饰器函数:

  1. 列出args,可能还有kwargs和
  2. 访问其装饰定义的方法类的实例?
  3. 因此对于@ajaxGet装饰器,self中有一个名为type的属性,其中包含我需要检查的值。

    由于

1 个答案:

答案 0 :(得分:11)

是。事实上,从某种意义上说,你似乎并不是真的有办法写一个可以访问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>