Python装饰器的预期寿命是多少? [英] What is the intended lifetime of a Python decorator?

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

问题描述

我的问题围绕着已实现的Python装饰器的预期寿命。在 realpython.org 中说:

My question revolves around the intended lifetime of an implemented Python decorator. From realpython.org it says:


''按照定义,装饰器是一个函数,它接受另一个函数
并扩展了后者的行为,而无需明确地
对其进行修改

''By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.''

在我看来,在线示例中经常使用装饰器来临时修改或扩展python函数,例如如html格式示例中所示。

To me, it seems like decorators quite frequently are used in examples online to temporarily modify or extend a python function, such as in the html formatting examples.

示例

假设我在一家Web开发公司工作,在我所有网页的顶部,我将此Python函数称为 page_welcome()

Let's say that I work at a web development company and at the top of all of my webpages I call this Python function page_welcome().

def page_welcome():
    return "Welcome to XYZ's company webpage!"

现在,一些开发人员加入了该公司,并决定我们应该通过修改功能来使这一点更加突出一些粗体斜体

Now, some developer joins the company and decides we should make this stand out more by modifying the function with some bold and italics.

def makebold(fn):
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped    

def makeitalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped    

@makebold
@makeitalic
def page_welcome():
    return "Welcome to XYZ's company webpage!"

如果我们确定此更改是永久性的,装饰者是否是保留此永久性修改的最佳方法? ?

If we decide this change is to be permanent, are decorators the best way of leaving in this permanent modification?

注意:上例是此链接的修饰器示例(稍作修改):
如何制作功能装饰器链?

Note: The example above is the decorator example from this link (modified slightly): How to make a chain of function decorators?

推荐答案

装饰者的主要目的不是临时修改功能行为。这里的临时一词很奇怪。最好将它们视为职责分解和代码重用。它们主要用于添加一些行为,这些行为并非唯一地绑定到装饰函数,也可以用于其他函数。一个很好的例子是 @memoized 装饰器,该装饰器记住装饰函数计算的值(这可能需要花费很多时间来计算),下一次立即返回该值。这样的装饰器可以重复使用很多次,除此之外,它还使核心更具可读性:与其用备忘录代码使函数膨胀,您还可以添加一行清楚地说明实际发生的事情。

Decorators' main purpose is not for temporary modification of function behaviour. The word "temporarily" is odd here. It is better to think about them as decomposition of responsibilities and code reuse. They are mostly used to add some behaviour which is not uniquely bound to decorating function and can be used for other functions too. One good example is the @memoized decorator, which remembers the value computed by the decorated function (which may take a lot of time to compute) and next time returns the value immediately. Such a decorator can be reused many times and, besides that, it makes core much more readable: instead of bloating your function with memoization code you add a single line which clearly states what actually happens.

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

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