11

我有一个定义如下的类:

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

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

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

因此,对于 @ajaxGet 装饰器,在self调用中有一个属性,type其中包含我需要检查的值。

谢谢

4

1 回答 1

16

是的。实际上,从您似乎的意思来看,实际上没有一种方法可以编写无法访问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>
于 2013-03-04T07:16:33.507 回答