Python-我可以在函数中使用decorator吗?

Python-我可以在函数中使用decorator吗?,python,python-decorators,Python,Python Decorators,我有两个问题。我已经创建了一个decorator来检查字典是否有键?给你 def check_has_key(func): def inner(x,y): # inner function needs parameters dictionary = {"add" : "true", "subtract" : "true"} if dictionary.has_key("add") : return func(x,y)

我有两个问题。我已经创建了一个decorator来检查字典是否有键?给你

def check_has_key(func):
    def inner(x,y): # inner function needs parameters
        dictionary = {"add" : "true", "subtract" : "true"}
        if dictionary.has_key("add") : 
            return func(x,y)
        return "Add not allowed"
    return inner # return the inner function (don't call it)

@check_has_key
def add(x,y):
    return x+y

print add(1,2)
1)我可以将密钥作为参数传递给包装器,然后检查它是否存在吗?例如:-就像我把键作为
@check\u has\u ket(“子动作”)
传递一样

2)我可以在函数中使用装饰器吗?就好像我需要检查字典是否有键一样,深入到函数的深处

编辑

我得到了第一个问题的答案

def abc(a):
    def check_has_key(func):
        def inner(x,y): # inner function needs parameters
            dictionary = {"add" : "true", "subtract" : "true"}
            if dictionary.has_key(a) : 
                return func(x,y)
            return "Add not allowed"
        return inner # return the inner function (don't call it)
    return check_has_key

@abc("subtract")
def add(x,y):
    return x+y

print add(1,2)

但我的疑问仍然存在,我能否在功能的深层使用装饰器?也就是说,如果我需要检查字典中是否存在键,我可以为此使用decorator,还是只使用if条件?

如果需要参数化decorator,可以定义一个类,通过
\uuuu init\uuuu
传入装饰程序的参数,并覆盖其
\uuu调用
函数。比如:

class decorate:

    def __init__(self, decorator_arg):
        self.decorator_arg = decorator_arg

    def __call__(self, func):
        def inner(x,y):
            # do something, probably using self.decorator_arg
            return func(x,y)
        return inner

@decorate("subtract")
def add(x,y):
    return x+y

对于第(2)项,如果您的功能中有其他功能需要装饰,则可以。如果您需要这样做,您可能只需要一个函数而不是装饰器。

为什么要在内部函数中定义字典?不会是字典。那么has_key将永远是真的吗?那么,您创建decorator函数的目标是什么?顺便说一句,你可以在定义函数的任何地方使用修饰语。(1)修饰语只在定义函数时使用,还是我也可以这样使用,意思是在行或代码之间?(2) 如果我在一个函数上有多个decorator,那么decorators的执行顺序是什么?也许这对decorators可能有帮助。阅读它,它就像你需要了解的关于decorators的一切。你对使用decorator“深入函数”还有疑问:你可以在任何地方使用它,可以通过(嵌套)函数定义上的@syntax,也可以显式修改现有的函数定义,即
foo=abc(“add”)(foo)
。我知道如果有嵌套函数,我可以使用decorator,但就我而言,没有嵌套函数。这只是一组简单的代码行。另外,请查看我编辑的问题,并检查我是否按我的方式完成了(1)。这是正确的方法吗?是的,你(1)的方法也很好。Decorator是用来修饰一个函数的,如果没有另一个函数,你根本不需要一个Decorator。您只需要另一个可以在多个位置重用的函数。如果修饰函数必须知道它已经修饰过,或者甚至需要触摸它的主体内部的装饰器,那么您使用装饰器的方式是错误的。如果我在一个函数上有多个装饰器,装饰器的执行顺序是什么?在注释中有点难以描述,但无论如何——最接近原始函数的装饰器(即装饰函数的
def
正上方)将首先包装原始函数,生成一个包装函数,然后由下一个上层装饰器包装,生成另一个函数,该函数。。。等等