简体   繁体   English

python装饰器是否只是装饰以下函数或下面的所有函数?

[英]Does a python decorator just decorate the following function or all functions beneath?

I've got a class definition as follows: 我有一个如下的类定义:

class myClass(object):
    @lru_cache(maxsize=None)
    def f1(self):
        return 1

    def f2(self):
        return 2

What I want to know is, does the @lru_cache decorator apply to all functions beneath until it hits another decorator, or just the following function? 我想知道的是, @lru_cache装饰器会应用于下面的所有功能,直到遇到另一个装饰器,还是仅以下函数?

If I want to decorate f2 , do I need to repeat @lru_cache above it as well? 如果要装饰f2 ,是否还需要在@lru_cache上面重复@lru_cache

You can easily test this out yourself, by definining a decorator that will tell you whether you decorated something. 您可以通过定义一个装饰器来轻松地自己测试一下,该装饰器将告诉您是否装饰了某些东西。 For example this one: 例如这个:

def myDecorator (f):
    print('Decorated {0}'.format(f.__name__))
    return f

Then, when used with your class: 然后,当与您的班级一起使用时:

class MyClass:
    @myDecorator
    def f1 (self):
        return 1

    def f2 (self):
        return 2

… you get the following output: …您将获得以下输出:

Decorated f1

So the decorator is only applied to the function it is directly decorating. 因此,装饰器仅应用于直接装饰的功能。 And if you think about it, this makes a lot of sense, since there is no syntax to undecorate a function. 如果考虑一下,这很有意义,因为没有语法可以取消修饰函数。 And since you can apply multiple decorators to single functions, there's also no concept of overwriting a decorator. 而且,由于您可以将多个装饰器应用于单个功能,因此也没有覆盖装饰器的概念。

And finally, as per the zen of Python , “explicit is better than implicit” . 最后,按照Python的禅定“显式比隐式好” So we rather want to explicitly list the decorator for every single function it should apply to instead of implicitly having rules that applies it in some magic way because it syntactically appeared before. 因此,我们宁愿明确为其应应用的每个函数列出装饰器,而不是隐式地具有以某种魔术方式应用装饰器的规则,因为它在语法上已经出现过。

Decorators only apply to the function following it, if it was the other way, what would happen if i didn't want to decorate the function? 装饰器仅适用于其后的功能,否则,如果我不想装饰该功能,会发生什么? so they only apply to the following function. 因此它们仅适用于以下功能。

So you have to use @lru_cahce on the f2 function if you want to cache it. 因此,如果要缓存它, @lru_cahcef2函数上使用@lru_cahce

In addition to poke's answer: how about looking at the formal syntax of function's definition? 除了戳的答案之外,如何看待函数定义的形式语法?

See https://docs.python.org/3/reference/compound_stmts.html#function-definitions . 请参阅https://docs.python.org/3/reference/compound_stmts.html#function-definitions

funcdef ::=  [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite

So any decorators modifying a function have to be listed directly before the line that starts with def . 因此,任何修饰函数的修饰符都必须在以def开头的行之前直接列出。 No other code can jump in between. 没有其他代码可以在两者之间跳转。

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

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