Python中的装饰器类 [英] Decorator classes in Python

查看:105
本文介绍了Python中的装饰器类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要构建用作装饰器的类,并保留以下原则:

I want to construct classes for use as decorators with the following principles intact:


  1. 应该有可能堆叠多个此类装饰器在顶部关闭1个函数。

  2. 所产生的函数名称指针应该与没有装饰器的相同函数没有区别,可能只是针对哪种类型/类。

  3. 除非装饰员实际授权,否则不应该指定装饰员。就是独立装饰器可以以任何顺序应用。

这是针对Django项目的,我现在正在研究的具体情况是需要2个装饰器,并显示为普通的python函数:

This is for a Django project, and the specific case I am working on now the method needs 2 decorators, and to appear as a normal python function:

@AccessCheck
@AutoTemplate
def view(request, item_id) {}

@AutoTemplate更改了该函数,因此无需返回HttpResponse,它只是返回在上下文中使用的字典。

@AutoTemplate changes the function so that instead of returning a HttpResponse, it just returns a dictionary for use in the context. A RequestContext is used, and the template name is inferred from the method name and module.

@AccessCheck根据item_id向用户添加其他检查。

@AccessCheck adds additional checks on the user based on the item_id.

我想这只是为了正确地构造函数并复制适当的属性,但是这些是哪些属性?

I am guessing it's just to get the constructor right and copy the appropriate attributes, but which attributes are these?

以下装饰器将无法像我描述的那样工作:

The following decorator won't work as I describe:

class NullDecl (object):
    def __init__ (self, func):
        self.func = func
    def __call__ (self, * args):
        return self.func (*args)

由以下代码演示:

@NullDecl
@NullDecl
def decorated():
    pass

def pure():
    pass

# results in set(['func_closure', 'func_dict', '__get__', 'func_name',
# 'func_defaults', '__name__', 'func_code', 'func_doc', 'func_globals'])
print set(dir(pure)) - set(dir(decorated));

另外,尝试在NullDecl中添加 print func。 name

Additionally, try and add "print func.name" in the NullDecl constructor, and it will work for the first decorator, but not the second - as name will be missing.

精炼的 eduffy 的答案a位,并且似乎工作得很好:

Refined eduffy's answer a bit, and it seems to work pretty well:

class NullDecl (object):
    def __init__ (self, func):
        self.func = func
        for n in set(dir(func)) - set(dir(self)):
            setattr(self, n, getattr(func, n))

    def __call__ (self, * args):
        return self.func (*args)
    def __repr__(self):
        return self.func


推荐答案

不做装饰器的类如下所示:

A do-nothing decorator class would look like this:

class NullDecl (object):
   def __init__ (self, func):
      self.func = func
      for name in set(dir(func)) - set(dir(self)):
        setattr(self, name, getattr(func, name))

   def __call__ (self, *args):
      return self.func (*args)

然后可以正常应用:

@NullDecl
def myFunc (x,y,z):
   return (x+y)/z

这篇关于Python中的装饰器类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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