Python Decorator
A decorator is an advanced feature in Python, used todynamically extend the functionality of functions or classes without modifying the original function's code。
Essentially, a decorator is a function: it receives a function as a parameter and returns a new function (usually an enhanced version of the original).

A decorator is applied before a function or method definition using the @decorator_name syntax.
Python also provides some built-in decorators, such as @staticmethod and @classmethod.
Common use cases:
- **Logging:** record function call information, parameters, and return values
- **Performance statistics:** measure function execution time
- **Access control:** restrict function access permissions
- **Caching:** cache function results to improve performance
Basic Syntax
The core idea of decorators is:Use one function to "wrap" another function。
Syntax
def
decorator_function
(
original_function
)
:
def
wrapper
(
*args
,
**kwargs
)
:
Before call
(
"Before execution"
)
result
=
original_function
(
*args
,
**kwargs
)
After call
(
"After execution"
)
return
result
return
wrapper
@
decorator_function
def
target_function
(
)
:
(
"Original function execution"
)
Analysis:
decorator_function: decorator function (receives the original function)wrapper: wrapper function (actually executed)@decorator_function: equivalent to function replacement
Equivalent syntax:
target_function = decorator_function(target_function)
👉 When calling target_function() , what actually executes is wrapper()
Using decorators
A decorator is applied before a function definition via the @ syntactic sugar:
@time_logger
def target_function():
pass
Equivalent to:
def target_function():
pass
target_function = time_logger(target_function)
This mechanism lets us uniformly add functionality (such as logging, permissions, etc.) without modifying the original function.
Example: printing logs
def
my_decorator
(
func
)
:
def
wrapper
(
)
:
(
"Before function execution"
)
func
(
)
(
"After function execution"
)
return
wrapper
@
my_decorator
def
say_hello
(
)
:
(
"Hello!"
)
say_hello
(
)
Output:
函数执行前
Hello!
函数执行后
my_decoratorreceivesay_hello@my_decoratorreplace the original function
Decorators with parameters
If the original function has parameters, you need to wrapper Using it in *args, **kwargs:
Example
def
my_decorator
(
func
)
:
def
wrapper
(
*args
,
**kwargs
)
:
(
"Before execution"
)
func
(
*args
,
**kwargs
)
(
"After execution"
)
return
wrapper
@
my_decorator
def
greet
(
name
)
:
(
f
"Hello, {name}!"
)
greet
(
"Alice"
)
Output:
执行前
Hello, Alice!
执行后
**Note:** using *args, **kwargs can be compatible with functions of any parameters.
Decorators with parameters (advanced)
def
repeat
(
num_times
)
:
def
decorator
(
func
)
:
def
wrapper
(
*args
,
**kwargs
)
:
for
_
in
range
(
num_times
)
:
func
(
*args
,
**kwargs
)
return
wrapper
return
decorator
@
repeat
(
3
)
def
say_hello
(
)
:
(
"Hello!"
)
say_hello
(
)
**Note:** this is a "decorator factory"; the outer function is used to receive parameters.
Hello!
Hello!
Hello!

Class decorators
Besides functions, decorators can also be applied to classes.
A class decorator receives a class and returns the modified or wrapped class.
- Enhance class methods
- Control the instantiation process
- Implement singleton, logging, and other features
Function-form class decorators
Example
def
log_class
(
cls
)
:
class
Wrapper:
def
init
(
self
,
*args
,
**kwargs
)
:
self
.
wrapped
=
cls
(
*args
,
**kwargs
)
def
getattr
(
self
,
name
)
:
return
getattr
(
self
.
wrapped
,
name
)
def
display
(
self
)
:
(
"Before call"
)
self
.
wrapped
.
display
(
)
(
"After call"
)
return
Wrapper
@
log_class
class
MyClass:
def
display
(
self
)
:
(
"Original method"
)
obj
=
MyClass
(
)
obj.
display
(
)
调用前
原方法
调用后
Class-form class decorators
Example: singleton pattern
class
SingletonDecorator:
def
init
(
self
,
cls
)
:
self
.
cls
=
cls
self
.
instance
=
None
def
call
(
self
,
*args
,
**kwargs
)
:
if
self
.
instance
is
None
:
self
.
instance
=
self
.
cls
(
*args
,
**kwargs
)
return
self
.
instance
@
SingletonDecorator
class
Database:
def
init
(
self
)
:
(
"Initialize"
)
db1
=
Database
(
)
db2
=
Database
(
)
(
db1
is
db2
)
初始化
True
Built-in decorators
Common built-in decorators:
- @staticmethod: define a static method
- @classmethod: define a class method
- @property: turn a method into a property
Example
class
MyClass:
@
staticmethod
def
static_method
(
)
:
(
"Static method"
)
@
classmethod
def
class_method
(
cls
)
:
(
cls.name
)
@
property
def
name
(
self
)
:
return
self
._name
@
name.
setter
def
name
(
self
,
value
)
:
self
._name
=
value
Stacking multiple decorators
Multiple decorators atwrap the function from bottom to top during the definition phase,execute from top to bottom during the call phase:
Example
def
decorator1
(
func
)
:
def
wrapper
(
)
:
(
"Decorator 1"
)
func
(
)
return
wrapper
def
decorator2
(
func
)
:
def
wrapper
(
)
:
(
"Decorator 2"
)
func
(
)
return
wrapper
@
decorator1
@
decorator2
def
say_hello
(
)
:
(
"Hello!"
)
say_hello
(
)
Final output:
Decorator 1
Decorator 2
Hello!
Core summary
装饰器 = 函数包装函数 + 不修改原代码扩展功能
- The @ syntax is essentially function replacement
- the wrapper is the function that actually executes
- It is recommended to use *args, **kwargs to improve generality
- Supports functions, classes, and even decorators with parameters