The method of passing the value of the closure function:
Method 1: Pass the value through the parameter
Func (x):
Print (x)
Func (1)
Method 2: Value of the closure function
def outter (x):
def Inner ():
Print (x)
return Inner
F=outter (1)
F ()
Adorner:
Decoration refers to adding additional functionality to the adorner object.
The implementation of the adorner must follow the principle of mass:
1. Do not modify the source code of the object being decorated
2. Do not modify the Decorated object debugging mode
Evolution of the non-parametric adorner:
Mode 1:
Import time
DefIndex ():
Time.sleep (3)
print ( ' Welcome to index page ')
def outter ( func ): #func = Initial index
# Func=index
def wrapper ():
Start_time= Time.time ()
func () # Call the most original index
Stop_time=time.time ()
print (stop_ Time-start_time)
return wrapper
Index=outter (index) #新的index =wrapper
Index () #wrapper
Mode 2: When the function is visible, think
Import time
# DEF index ():
# Time.sleep (1)
# print (' Welcome to index page ')
# return 123
DefHome (name):
Time.sleep (2)
Print' Welcome%s to home page '%name)
#============== Decorator
DefOutter (func):#func = Initial Index
# Func=index
Defwrapper (name):
Start_time=time.time ()
Res=func (name) # Calling the most primitive index also calls the most primitive home, but when the home is passed the value is the physical parameter name inside the
Stop_time=time.time ()
print (stop_time-start_time)
return res
return wrapper
# index=outter (Index) #新的index =wrapper
# index ()
Home=outter (Home) Span style= "COLOR: #808080" > #新的home =wrapper
home ( ' Yangzhizong ')
Mode 3:
Import time
DefIndex ():
Time.sleep (1)
Print' Welcome to index page ')
DefHome (name):
Time.sleep (2)
Print' Welcome%s to home page '%name)
#============== Decorator
DefTimmer (func):#func = The initial index and the most initial home
# Func=index
DefWrapper(*args, **kwargs):
Start_time=time.time ()
Res=func(*args , **kwargs) The #调用最原始的index also calls the original home, but the home is in the value of the physical parameter name in the
Stop_time=time.time ()
Print (Stop_time-start_time)
return res
return Wrapper
Index=timmer (index) #新的index =wrapper
Index ()
Home=timmer (home) #新的home =wrapper
Home (' Yangzhizong ')
Mode 4: Final version
Import time
DefTimmer (func):
DefWrapper (*args, **kwargs):
Start_time=time.time ()
Res=func (*args, **kwargs)
Stop_time=time.time ()
Print (Stop_time-start_time)
return res
Return wrapper
@timmer #index =timmer (Index)
def index ():
Time.sleep (1)
print (' Welcome to index page ')
@timmer #home =timmer (home)
def Home (name):
Time.sleep (2)
print (' Welcome%s to home page '%name)
Index ()
Home (' Yangzhizong ')
Adorner: (Fixed and unchanging writing format)
outer (func):
Inner (*args, **kwargs):
Res=fun (*args, **kwargs)
return res
Res inner
Python closure function, adorner