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

Mic*_*tes 6 python decorator python-2.7

我有一个类定义如下:

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

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

  1. 取一个args列表,可能还有kwargs,和
  2. 访问其装饰定义的方法的类的实例?

所以对于@ajaxGet装饰器,在self被调用的属性中type包含我需要检查的值.

谢谢

Bre*_*arn 13

是.事实上,从某种意义上说,你似乎并不是真的有办法编写一个无法访问的装饰器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
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它:

>>> 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>
Run Code Online (Sandbox Code Playgroud)