程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How do I understand Python decorators in a straightforward way? How do you use it?

編輯:Python

Catalog

One 、 Decorator

1. Definition of decorator

2. Decorator example code

3. The grammar of decorators is sugar

Two 、 The use of decorators

1. The use of decorators

2. Decorator implements the statistics of existing function execution time

  3、 ... and 、 The use of universal decorators

1. Decorate functions with parameters

2. Decorate a function with a return value

3. Decorate functions with indefinite length parameters

4. Universal decorator

Four 、 The use of multiple decorators

1. Example code for using multiple decorators

5、 ... and 、 Decorator with parameters

1. Introduction to decorator with parameters

  6、 ... and 、 Class decorator

1. Class decorator


One 、 Decorator

1. Definition of decorator

Namely A function that adds additional functionality to an existing function , It's essentially a closure function .

The features of decorators are :

  1. Do not modify the source code of the existing function
  2. Do not modify the calling method of existing functions
  3. Add extra functionality to existing functions

2. Decorator example code

# Add a login verification function
def check(fn):
def inner():
print(" Please log in first ....")
fn()
return inner
def comment():
print(" Comment ")
# Use decorators to decorate functions
comment = check(comment)
comment()
# The basic prototype of the decorator
# def decorator(fn): # fn: Objective function .
# def inner():
# ''' Before executing the function '''
# fn() # Execute the decorated function
# ''' After executing the function '''
# return inner

Code instructions :

  • Closure function has and only has one parameter , Must be a function type , The function defined in this way is the decorator .
  • Write code to follow the principle of open and closed , It stipulates that the implemented function code is not allowed to be modified , But it can be expanded .

Execution results :

 Please log in first ....
Comment

3. The grammar of decorators is sugar

If there are multiple functions that need to add login authentication function , Every time you need to write func = check(func) This code decorates the existing functions , This method is still more troublesome .

Python To provide a decoration function more simple writing , That's grammar sugar , Grammar sugar is written in the form of : @ Decorator name , The decoration of existing functions can also be completed by the way of syntax sugar

# Add a login verification function
def check(fn):
print(" The decorator function executes ")
def inner():
print(" Please log in first ....")
fn()
return inner
# Use syntax sugar to decorate functions
@check
def comment():
print(" Comment ")
comment()

explain :

  • @check Equivalent to comment = check(comment)
  • The execution time of the decorator is executed immediately when the module is loaded .

Execution results :

 Please log in first ....
Comment

Two 、 The use of decorators

1. The use of decorators

  1. Statistics of function execution time
  2. Output log information

2. Decorator implements the statistics of existing function execution time

import time
# Decorator function
def get_time(func):
def inner():
begin = time.time()
func()
end = time.time()
print(" Function execution cost %f" % (end-begin))
return inner
@get_time
def func1():
for i in range(100000):
print(i)
func1()

Execution results :


...
99995
99996
99997
99998
99999
Function execution cost 0.329066

  3、 ... and 、 The use of universal decorators

1. Decorate functions with parameters

# Add the function of outputting log
def logging(fn):
def inner(num1, num2):
print("-- Trying to calculate --")
fn(num1, num2)
return inner
# Use decorators to decorate functions
@logging
def sum_num(a, b):
result = a + b
print(result)
sum_num(1, 2)

Running results :

-- Trying to calculate --
3

2. Decorate a function with a return value

# Add the function of outputting log
def logging(fn):
def inner(num1, num2):
print("-- Trying to calculate --")
result = fn(num1, num2)
return result
return inner
# Use decorators to decorate functions
@logging
def sum_num(a, b):
result = a + b
return result
result = sum_num(1, 2)
print(result)

Running results :

-- Trying to calculate --
3

3. Decorate functions with indefinite length parameters

# Add the function of outputting log
def logging(fn):
def inner(*args, **kwargs):
print("-- Trying to calculate --")
fn(*args, **kwargs)
return inner
# Use syntax sugar to decorate functions
@logging
def sum_num(*args, **kwargs):
result = 0
for value in args:
result += value
for value in kwargs.values():
result += value
print(result)
sum_num(1, 2, a=10)

Running results :

-- Trying to calculate --
13

4. Universal decorator

# Add the function of outputting log
def logging(fn):
def inner(*args, **kwargs):
print("-- Trying to calculate --")
result = fn(*args, **kwargs)
return result
return inner
# Use syntax sugar to decorate functions
@logging
def sum_num(*args, **kwargs):
result = 0
for value in args:
result += value
for value in kwargs.values():
result += value
return result
@logging
def subtraction(a, b):
result = a - b
print(result)
result = sum_num(1, 2, a=10)
print(result)
subtraction(4, 2)

Running results :

-- Trying to calculate --
13
-- Trying to calculate --
2

# Universal decorator
def logging(fn):
def inner(*args, **kwargs):
print("-- Trying to calculate --")
result = fn(*args, **kwargs)
return result
return inner

Four 、 The use of multiple decorators

1. Example code for using multiple decorators

def make_div(func):
""" The return value of the decorated function div label """
def inner():
return "<div>" + func() + "</div>"
return inner
def make_p(func):
""" The return value of the decorated function p label """
def inner():
return "<p>" + func() + "</p>"
return inner
# Decoration process : 1 content = make_p(content) 2 content = make_div(content)
# content = make_div(make_p(content))
@make_div
@make_p
def content():
return " Life is too short "
result = content()
print(result)

Code instructions :

  • The decoration process of multiple decorators is : The decorator closest to the function decorates first , Then the outer decorator will decorate , Decoration process from inside to outside

5、 ... and 、 Decorator with parameters

1. Introduction to decorator with parameters

The decorator with parameters is that you can pass in the specified parameters when decorating functions with decorators , Grammar format : @ Decorator ( Parameters ,...)

Wrong writing :

def decorator(fn, flag):
def inner(num1, num2):
if flag == "+":
print("-- Trying to add --")
elif flag == "-":
print("-- Trying to subtract --")
result = fn(num1, num2)
return result
return inner
@decorator('+')
def add(a, b):
result = a + b
return result
result = add(1, 3)
print(result)

Execution results :

Traceback (most recent call last):
File "/home/python/Desktop/test/hho.py", line 12, in <module>
@decorator('+')
TypeError: decorator() missing 1 required positional argument: 'flag'

Code instructions :

  • Decorator can only accept one parameter , And it is also a function type .

Write it correctly :

Wrap a function around the decorator , Let the outermost function take arguments , Decorator returned , because @ The symbol must be followed by a decorator instance .

# Add the function of outputting log
def logging(flag):
def decorator(fn):
def inner(num1, num2):
if flag == "+":
print("-- Trying to add --")
elif flag == "-":
print("-- Trying to subtract --")
result = fn(num1, num2)
return result
return inner
# Return to the decorator
return decorator
# Use decorators to decorate functions
@logging("+")
def add(a, b):
result = a + b
return result
@logging("-")
def sub(a, b):
result = a - b
return result
result = add(1, 2)
print(result)
result = sub(1, 2)
print(result)

  6、 ... and 、 Class decorator

1. Class decorator

There is also a special use of decorators, that is, class decorators , Is to decorate the function by defining a class .

Class decorator sample code :

class Check(object):
def __init__(self, fn):
# The initialization operation is completed here
self.__fn = fn
# Realization __call__ Method , Indicates that the object is a callable object , It can be called like a function .
def __call__(self, *args, **kwargs):
# Add decoration function
print(" Please log in first ...")
self.__fn()
@Check
def comment():
print(" Comment ")
comment()

Code instructions :

  • @Check Equivalent to comment = Check(comment), So we need to provide a init Method , And add one more fn Parameters .
  • If you want an instance object of a class to be able to call... Like a function , You need to use... In the class call Method , Turn an instance of a class into a callable object (callable), In other words, it can be called like a function .
  • stay call Method fn Decoration of function , Additional functions can be added .

Execution results :

 Please log in first ...
Comment 

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved