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
Namely A function that adds additional functionality to an existing function , It's essentially a closure function .
The features of decorators are :
# 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 :
Execution results :
Please log in first ....
Comment
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 :
Execution results :
Please log in first ....
Comment
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
# 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
# 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
# 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
# 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
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 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 :
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)
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 :
Execution results :
Please log in first ...
Comment