简体   繁体   English

使用装饰器和直接应用 function 有什么区别吗?

[英]Is there any difference between using a decorator and applying the function directly?

I recently became the maintainter of PyPDF2 - a library which is pretty old and still has some code that deals with Python versions before 2.4 .我最近成为 PyPDF2 的维护者 - 一个相当古老的库,仍然有一些代码处理2.4 之前的 Python 版本。 While I want to drop support for 3.5 and older soon, I see some parts where I'm uncertain why they were written as they are.虽然我想尽快放弃对 3.5 及更早版本的支持,但我看到有些部分我不确定为什么要按原样编写。

One example is this:一个例子是这样的:

What is in the code:代码中的内容:

class Foo(object):
    def a(b, c):
        print(b)
        print(c)

    a = staticmethod(a)

What I would expect instead:我期望的是:

class Bar(object):
    @staticmethod
    def a(b, c):
        print(b)
        print(c)

Is there any reason to use the first notation?有什么理由使用第一种表示法吗? Are they strictly equivalent?它们是严格等价的吗?

I've seen that decorators were introduced in Python 2.4 , so this might be an example of such extreme legacy code.我已经看到装饰器是在 Python 2.4 中引入的,所以这可能是这种极端遗留代码的一个例子。

The first version is just the pre-2.4 way to use staticmethod .第一个版本只是使用staticmethod的 pre-2.4 方式。 The two versions aren't quite equivalent, but the difference is so tiny it almost never matters.这两个版本并不完全相同,但差异是如此之小以至于几乎无关紧要。

Specifically, on Python versions that support decorator syntax, the one difference is that the second version passes the original function directly to staticmethod , while the first version stores the original function to a and then looks up the a variable to find the argument to pass to staticmethod .具体来说,在支持装饰器语法的 Python 版本上,一个区别是第二个版本将原始 function 直接传递给staticmethod ,而第一个版本将原始 function 存储到a ,然后查找a变量以找到要传递给的参数staticmethod This can technically matter in very weird use cases, particularly with metaclasses, but it'd be highly unlikely.从技术上讲,这在非常奇怪的用例中可能很重要,尤其是对于元类,但这不太可能。 Python 2 doesn't even support the relevant metaclass feature ( __prepare__ ). Python 2 甚至不支持相关的元类功能 ( __prepare__ )。

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

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