简体   繁体   English

如何创建具有装饰器属性的装饰器?

[英]How to create a decorator with decorator attributes?

I have seen decorators like this, how do I create them?我见过这样的装饰器,我该如何创建它们?

@deco.deco_attribute
def add(a, b):
    return a + b

I know how to create a decorator, that looks something like this我知道如何创建一个装饰器,它看起来像这样

import time

def timer(func):
    def wrapper(*args, **kwargs):
        time_in = time.time()
        x = func(*args, **kwargs)
        time_out = time.time()
        print(time_out - time_in)
        return x
    return wrapper

@timer
def add(a, b):
    return a + b

and have even seen examples of adding arguments to a decorator, which could be accomplished using nested functions.甚至看过将 arguments 添加到装饰器的示例,这可以使用嵌套函数来完成。


def timer(*deco_args):
    def inner(func):
        def wrapper(*args, **kwargs):
            time_in = time.time()
            x = func(*args, **kwargs)
            time_out = time.time()
            print(*deco_args, time_out - time_in)
            return x
        return wrapper
    return inner

@timer(2, 3)
def add(a, b):
    return a + b

Other variations that I am aware of include, nesting multiple decorators or creating a class as a decorator, or creating a function as a decorator for a class.我知道的其他变体包括嵌套多个装饰器或创建 class 作为装饰器,或创建 function 作为 class 的装饰器。

But how to create the decorator mentioned on top?但是如何创建上面提到的装饰器呢?

You can use class and put every decorator inside it您可以使用 class 并将所有装饰器放入其中

class deco():
  @staticmethod
  def time_1(func):
    def inner():
      return 0 
    return inner

  @staticmethod
  def time_2(func):
    def inner():
      return 0 
    return inner


@deco.time_1
def test():
  return 4+5

I think its just a matter of how you do the import.我认为这只是您如何进行导入的问题。 In your example you would have only imported the module import deco and then accessed the decorator inside that module as you would with any other function. One place I often see the module being imported rather the decorator is pytest fixtures:在您的示例中,您将只导入模块import deco ,然后像访问任何其他 function 一样访问该模块内的装饰器。我经常看到导入模块而不是装饰器的一个地方是 pytest 固定装置:

import pytest

@pytest.fixture
def my_fixture():
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM