Decorator : A function that adds additional functionality to an existing function , It's essentially a closure function
characteristic :
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
4. Parsing decorator before code execution
# @Author : Kant
# @Time : 2022/1/23 18:06
'''
Decorator : A function that adds additional functionality to an existing function , It's essentially a closure function
characteristic :
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
4. Parsing decorator before code execution
'''
import time
# Decorator principle
# def show():
# n=0
# for i in range(10000000):
# n+=i
# print('show_',n)
#
# # Define a closure
# def count_time(fun):
# def inner():
# start=time.time()
# fun()
# end=time.time()
# print(f' when {end-start} second ')
# return inner
#
# # The principle of decorator in decorating function
# show=count_time(show)
# show()
# Define decorators ( Grammatical sugar )
def count_time(fun): # There must be a parameter to receive the decorated function
def inner():
start=time.time()
fun()
end=time.time()
print(f' when {end-start} second ')
return inner
# How to write ornaments :@ External functions of closures , Must be used after closure
print(' Analysis decorator 1')
@count_time # Interpreted as show=count_time(show),show Point to count_time Function inner
def show():
n=0
for i in range(10000000):
n+=i
print('show_',n)
print(' Analysis decorator 2')
@count_time # Interpreted as display=count_time(display)
def display():
print('Display')
print(' Formal implementation ...')
show()
display()
# @Author : Kant
# @Time : 2022/1/23 20:46
'''
Definition of a generic type of decorator ( The same applies when the decorated function has parameters or return values )
'''
def outer(func):
def inner(*args,**kwargs): # * Unpack tuples and lists ,** Unpack the dictionary
print('*'*30)
print(args,kwargs)
ret=func(*args,**kwargs) # Unpack , Otherwise, the formal parameter is a tuple or dictionary
print('*'*30)
return ret
return inner
@outer
def show(name,msg):
return str(name)+' say: '+str(msg)
print(show('Tom',msg='Hello'))
# @Author : Kant
# @Time : 2022/1/23 21:20
# The first closure
def wrapper_div(func):
def inner(*args,**kwargs):
return '<div>'+func(*args,**kwargs)+'</div>'
return inner
# The second closure
def wrapper_p(func):
def inner(*args,**kwargs):
return '<p>'+func(*args,**kwargs)+'</p>'
return inner
# Decorate from the bottom up , From top to bottom
@wrapper_div
@wrapper_p
# Define a function
def show():
return 'Short life I use Python.'
print(show()) #<div><p>Short life I use Python.</p></div>
# @Author : Kant
# @Time : 2022/1/23 21:44
def outer1(func):
def inner():
print(' Decorator 1-1')
func()
print(' Decorator 1-2')
return inner
def outer2(func):
def inner():
print(' Decorator 2-1')
func()
print(' Decorator 2-2')
return inner
'''
1.show Point to outer1.inner
2.outer1.inner.func Point to outer2.inner
3.outer2.inner.func Point to show
'''
@outer1
@outer2
def show():
print('Show...')
show()
# @Author : Kant
# @Time : 2022/1/23 22:17
import time
class Wrapper():
def __init__(self,func):
self.func=func
# When this method is implemented in the class , The instance object of this class becomes a callable object , That is, you can add... After the instance object ()
def __call__(self, *args, **kwargs):
print(' Decorative content 1...')
start=time.time()
ret=self.func(*args,**kwargs)
end=time.time()
print(f' Yes {end-start} second ')
print(' Decorative content 2...')
return ret
'''
When the decorator is finished , The decorated function points to the instance object of this class
If you let the decorated function execute , Then add... To the class __call__ Method , Equivalent to the inner function in the closure format
Once the decorated function executes the call , Then it will execute the... In the instance object __call__ function
'''
@Wrapper # Interpreted as show=Wrapper(show),show Becomes an object of a class
def show():
print('Show...')
show()
# @Author : Kant
# @Time : 2022/1/23 22:43
def set_args(msg):
def outer(func):
def inner():
print(' Decorative content ',msg)
func()
return inner
return outer
'''
Use decorators with parameters , In fact, there is a function wrapped around the decorator , Use this function to receive parameters , Decorator returned
call set_args() Will return to outer Address reference for , Turned into @outer
'''
@set_args('Hello')
# No matter what the closure function looks like , The decorated function always points to the inner function of the closure function
def show():
print('Show...')
show()
# @Author : Kant
# @Time : 2022/1/23 23:02
'''
route : Through a path , You can find the address of a resource
'''
# Define a routing table Dictionary
router_table={}
def router(url):
def wrapper(func):
def inner():
print('1')
print('inner-',func) # View who the current decorated function is
func()
# Maintain the routing table dictionary here
router_table[url]=inner # If write func,inner Nothing in the function will be executed
print(' Routing table dictionary :',router_table)
return inner
return wrapper
@router('index.html')
def index():
print(' Home page content ')
@router('center.html')
def center():
print(' Personal center ')
@router('mail.html')
def mail():
print(' Email page ')
@router('login.html')
def login():
print(' The login page ')
def error():
print(' The access page does not exist ')
def request_url(url):
func=error
if url in router_table:
func=router_table[url]
func()
print(' Start function ')
request_url('index.html')
request_url('center.html')
request_url('mail.html')
request_url('test.html')
request_url('login.html')