装饰器模式(Decorator Pattern)是一种设计模式,它允许你通过将对象放入包装对象中来为原对象添加新的行为。装饰器模式是一种替代继承的技术,它通过一种无需子类化增加功能的方式来扩展类的功能。
使用 decorators,可以在不直接修改源码的情况下修改 function 或 method 的功能,从而让代码更简洁,更 Pythonic
The fundamentals
functions in python
python 中函数是 first-class object,可以赋值给变量、作为参数传递、作为返回值、在运行时动态创建和修改,结合内置的装饰器,可以方便地实现横切关注点,无需额外的 AOP 库。
- being expressible as an anonymous literal value
- being storable in variables
- being storable in data structures
- having an intrinsic identity (independent of any given name)
- being comparable for equality with other entities
- being passable as a parameter to a procedure/function
- being returnable as the result of a procedure/function
- being constructible at runtime
- being printable
- being readable
- being transmissible among distributed processes
- being storable outside running processes
如下是使用 Python 中函数特性的例子:
Simple Demo
结合以上特性,可以实现一个简单的装饰器,实现计时功能
Tips: 建议使用 functools.wraps
保留原函数的元信息,如__name__、__doc__
等
Chaining Decorators
Python 允许使用多个装饰器,可以通过 @decorator1
@decorator2
… @decoratorN
的方式来实现
Best Practices(?)
- Parameter Validation Decorators
- Method Routing
- Caching and Memoization
- …
@lru_cache
getter/setter
Ref
What are “first-class” objects? —— StackOverFlow