带参数和访问类实例的Python装饰器

带参数和访问类实例的Python装饰器,python,python-2.7,decorator,Python,Python 2.7,Decorator,我有一个定义如下的类: class SomeViewController(BaseViewController): @requires('id', 'param1', 'param2') @ajaxGet def create(self): #do something here 是否可以编写一个decorator函数: 获取arg的列表,可能还有kwarg,以及 访问定义其装饰的方法所在的类的实例 因此,对于@ajaxGet decorator,self

我有一个定义如下的类:

class SomeViewController(BaseViewController):
    @requires('id', 'param1', 'param2')
    @ajaxGet
    def create(self):
        #do something here
是否可以编写一个decorator函数:

  • 获取arg的列表,可能还有kwarg,以及
  • 访问定义其装饰的方法所在的类的实例
  • 因此,对于@ajaxGet decorator,
    self
    中有一个名为
    type
    的属性,其中包含我需要检查的值


    谢谢

    是的。事实上,从你的意思来看,没有一种方法可以编写一个没有访问
    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>
    
    >f=Foo()
    >>>f.甲基苯丙胺()
    我是装饰师,我知道赛尔夫是,我可以用它做任何我想做的事!
    我还得到了其他参数:(){}
    我是方法,我自己是
    >>>f.meth('blah',stuff='crud')
    我是装饰师,我知道赛尔夫是,我可以用它做任何我想做的事!
    我还得到了其他参数:(u'blah',){'stuff':u'crud}
    我是方法,我自己是
    
    取决于您的意思。装饰器本身不能访问
    self
    ,因为装饰发生在类的定义过程中,在任何实例存在之前。但是作为装饰器结果的包装函数在调用实例时会知道该实例。你能举一个你想要实现的例子吗?所以当我在
    SomeViewController
    上调用
    create
    时,修饰的方法可以访问
    self
    (它被传递到
    create
    ,所以使用该对象是可能的),还可以使用参数对
    self
    上的其他属性执行检查,谢谢。有没有办法让装饰者接受参数进行检查?如果你能回答这个问题,我会让你的答案成为公认的答案。你说的“接受参数进行检查”是什么意思?装饰器必须接受一些参数,然后在装饰器函数中根据
    self
    进行检查。不过,我已经解决了这个问题,装饰函数必须包装在另一个函数中。我想他应该是这样的“@requires('id','param1','param2')”。若是这样,那个么问题就不会重复了,你们只需要将本文中的decorator包装成附加的函数,该函数接受可以在其中任何函数中使用的参数。例如,def decorator(foo):def meth_wrap(meth):def params_wrap(self,*args,**kwargs):self.foo=foo返回meth(self,*args,**kwargs)返回参数返回meth_wrap