2022-04-18 装饰器

Python 装饰器 概念

这个概念本身就相当地难理解。 感觉它的定义和它的名称还是有差距。

1. 首先要理解“装饰器”(decorator)

What is a Decorator?

A decorator is the name used for a software design pattern. Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated.

装饰器是一种软件设计模式,在不用子类或者修改原代码的前提下,自动地改变函数、方法或者类的功能。

2. 理解Python 装饰器

What is a Python Decorator?

The "decorators" we talk about with concern to Python are not exactly the same thing as the DecoratorPattern described above. A Python decorator is a specific change to the Python syntax that allows us to more conveniently alter functions and methods (and possibly classes in a future version).

Python 装饰器 与上面提到的装饰器模式还是有差别的。Python 装饰器其实是一个很特别语法修改,让我们更方便地改变函数或者方法(在未来的版本中,有可能包含修改类)。

装饰器有什么用?

装饰器有什么用,或者说我们在什么场景下需要不改变原函数或方法的代码,不使用子类,而又要改变函数或方法的功能呢?

由于我不是大神,所以只能从网上捞一些大神的答复。我是被说服了。总体来说,就几个点:

1) 方便套在其他函数上面

2) 不用重复写同样功能的代码

3) 临时性的添加一些功能,又不修改原代码,比如测试或者debug时

4) 增加代码的易读性

Because then for each combination of the decorator functions you have you will have to write another decorator function. Compositing decorator functions are the abstraction so you don't have to manually write those combinations yourself. – Netwave Oct 1, 2018 at 14:47

Package a decorator (or multiple), and you can easily apply all that functionality to other packages, without having to write new functions in those other packages: just one extra line for the relevant functions. – 9769953 Oct 1, 2018 at 14:49

And yes, technically you can precisely do what you suggest. But it makes things more cumbersome, and pollutes the code with extra functions. A decorator with clear functionality (from its name) makes code more readable, instead of having to read one function, only to then look up the other function. – 9769953 Oct 1, 2018 at 14:50 1

I'm not exactly an expert on design patterns, but I think Python decorators are not the same as the decorator pattern. (Maybe they are related at an abstract level, but the dup-targets do not seem to be practically relevant for this question.) – MB-F Oct 1, 2018 at 14:58

Decorators are very common when the function modification is temporary. Consider the use of decorators in adding testing or timing functions. – Michael Molter Oct 1, 2018 at 15:01

如何使用装饰器

这个问题,我找了很多网上的资料,以下这个比较容易懂。

https://pythonbasics.org/decorators/


你可能感兴趣的:(2022-04-18 装饰器)