装饰器的目的是什么(为什么使用它们)? [英] What is the purpose of decorators (why use them)?

查看:49
本文介绍了装饰器的目的是什么(为什么使用它们)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习和试验装饰器.我理解它们的作用:它们允许您在不更改现有函数的情况下向现有函数添加功能,从而编写模块化代码.

I've been learning and experimenting with decorators. I understand what they do: they allow you to write modular code by allowing you to add functionality to existing functions without changing them.

我找到了一个很棒的帖子,它通过在这里解释了所有的来龙去脉,真正帮助我学习了如何去做:如何制作函数装饰器链?

I found a great thread which really helped me learn how to do it by explaining all the ins and outs here: How to make a chain of function decorators?

但是这个线程(以及我看过的其他资源)缺少的是为什么我们需要装饰器语法?为什么我需要嵌套函数来创建装饰器?为什么我不能只使用一个现有的函数,编写另一个具有一些额外功能的函数,然后将第一个输入第二个以使其做其他事情?

But what is missing from this thread (and from other resources I've looked at) is WHY do we need the decorator syntax? Why do I need nested functions to create a decorator? Why can't I just take an existing function, write another one with some extra functionality, and feed the first into the 2nd to make it do something else?

仅仅是因为这是惯例吗?我错过了什么?我想我的经验不足.

Is it just because this is the convention? What am I missing? I assume my inexperience is showing here.

推荐答案

来自 PEP 318 -- 函数和方法的装饰器(加上我自己的重点):

From PEP 318 -- Decorators for Functions and Methods (with my own added emphasis):

当前将转换应用于一个的方法函数或方法将实际转换放在函数之后身体.对于大型函数这分离了从函数的其余部分的定义来看函数的行为外部接口.例如:

Motivation

The current method of applying a transformation to a function or method places the actual transformation after the function body. For large functions this separates a key component of the function's behavior from the definition of the rest of the function's external interface. For example:

def foo(self):
    perform method operation 
foo = classmethod(foo) 

这变得使用更长的方法时可读性降低.名称似乎也比pythonic少概念上单一的函数的三倍声明.解决这个问题的方法是移动转换更接近方法自身声明的方法.的意图新的语法是替换

This becomes less readable with longer methods. It also seems less than pythonic to name the function three times for what is conceptually a single declaration. A solution to this problem is to move the transformation of the method closer to the method's own declaration. The intent of the new syntax is to replace

def foo(cls):
    pass 
foo = synchronized(lock)(foo) 
foo = classmethod(foo)

另一种方法是将装饰放在函数声明中:

with an alternative that places the decoration in the function's declaration:

@classmethod
@synchronized(lock)
def foo(cls):
    pass

这篇关于装饰器的目的是什么(为什么使用它们)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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