Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Decorator

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:


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

       

print

(

"Before execution"

)

        result

=

original_function

(

*args

,

**kwargs

)

       

After call

       

print

(

"After execution"

)

       

return

result

   

return

wrapper

@

decorator_function

def

target_function

(

)

:

   

print

(

"Original function execution"

)

Analysis:

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

(

)

:

       

print

(

"Before function execution"

)

        func

(

)

       

print

(

"After function execution"

)

   

return

wrapper

@

my_decorator

def

say_hello

(

)

:

   

print

(

"Hello!"

)

say_hello

(

)

Output:


函数执行前
Hello!
函数执行后

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

)

:

       

print

(

"Before execution"

)

        func

(

*args

,

**kwargs

)

       

print

(

"After execution"

)

   

return

wrapper

@

my_decorator

def

greet

(

name

)

:

   

print

(

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

(

)

:

   

print

(

"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.


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

)

:

           

print

(

"Before call"

)

           

self

.

wrapped

.

display

(

)

           

print

(

"After call"

)

   

return

Wrapper

@

log_class

class

MyClass:

   

def

display

(

self

)

:

       

print

(

"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

)

:

       

print

(

"Initialize"

)

db1

=

Database

(

)

db2

=

Database

(

)

print

(

db1

is

db2

)


初始化
True

Built-in decorators

Common built-in decorators:

  1. @staticmethod: define a static method
  2. @classmethod: define a class method
  3. @property: turn a method into a property

Example

class

MyClass:

   

@

staticmethod

   

def

static_method

(

)

:

       

print

(

"Static method"

)

   

@

classmethod

   

def

class_method

(

cls

)

:

       

print

(

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

(

)

:

       

print

(

"Decorator 1"

)

        func

(

)

   

return

wrapper

def

decorator2

(

func

)

:

   

def

wrapper

(

)

:

       

print

(

"Decorator 2"

)

        func

(

)

   

return

wrapper

@

decorator1

@

decorator2

def

say_hello

(

)

:

   

print

(

"Hello!"

)

say_hello

(

)

Final output:


Decorator 1
Decorator 2
Hello!

Core summary


装饰器 = 函数包装函数 + 不修改原代码扩展功能