带有参数和访问类实例的Python Decorator [英] Python Decorator with arguments and accessing class instance

查看:75
本文介绍了带有参数和访问类实例的Python Decorator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义如下的类:

I have a class defined as follows:

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

是否可以编写装饰器函数?

Is it possible to write a decorator function that:


  1. 获取args列表,可能还有kwargs,并且

  2. 访问该类的实例,该实例的修饰方法定义在其中?

因此对于@ajaxGet装饰器,在 self 中有一个名为 type 的属性,其中包含值I

So for the @ajaxGet decorator, there is a attribute in self called type which contains the value I need to check.

谢谢

推荐答案

是。实际上,按照您的意思,实际上没有一种方法可以编写没有可以访问自身的装饰器。 。装饰的函数包装了原始函数,因此它必须至少接受该函数接受的参数(或可以从中导出参数的某些参数),否则无法将正确的参数传递给基础函数。

Yes. In fact, in the sense you seem to mean, there isn't really a way to write a decorator that doesn't have access to self. The decorated function wraps the original function, so it has to accept at least the arguments that that function accepts (or some arguments from which those can be derived), otherwise it couldn't pass the right arguments to the underlying function.

您不需要做任何特别的事情,只需编写一个普通的装饰器即可:

There is nothing special you need to do to do this, just write an ordinary decorator:

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>

这篇关于带有参数和访问类实例的Python Decorator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆