One, no parameter decorator
1 Open Closure principle
Once the software is online, it should follow the open closure principle, that is, to modify the source code is closed, the expansion of the function is open
That means we have to find a solution:
Ability to add new functionality without modifying a feature source code and calling mode
Summarize
The principles are as follows:
1, do not modify the source code
2. Do not modify the calling method
Objective:
Extend new functionality based on adherence to the 1 and 2 principles
2. What is an adorner?
A tool that refers to the addition of new features to a decorated object.
Full meaning:
The adorner adds new functionality to the adorner object without modifying the source code and calling method of the object being decorated.
The adorner and the decorated object can be any callable object
Adorner = "function
object to be decorated = "function
‘‘‘
Import Time #调用时间方法
def index ():
Start_time=time.time () #设定开始时间
Time.sleep (3) #暂停3秒
Print (' Welcome to index page ')
Stop_time=time.time () #设定结束时间
Print (' Run time is%s '% (stop_time-start_time)) #开始时间减结束时间, equal to
Index ()
#修订1:
Import time
def index ():
Time.sleep (3)
Print (' Welcome to index page ')
def home (name):
Time.sleep (5)
Print (' Welcome%s to home page '%name)
Start_time=time.time () #将时间操作单独拿出使用
Index ()
Stop_time = Time.time ()
Print (' Run time is%s '% (stop_time-start_time))
Start_time=time.time ()
Home (' Egon ')
Stop_time = Time.time ()
Print (' Run time is%s '% (stop_time-start_time))
#修订2:
Import time
def index ():
Time.sleep (3)
Print (' Welcome to index page ')
def home (name):
Time.sleep (5)
Print (' Welcome%s to home page '%name)
def wrapper (func): #func =index #把时间操作放到函数中
Start_time=time.time ()
Func () #index ()
Stop_time = Time.time ()
Print (' Run time is%s '% (stop_time-start_time))
Wrapper (Index) # modified the way the original function was called
#修订3:
Import time
def index (): #原index函数
Time.sleep (3)
Print (' Welcome to index page ')
def outter (func): #func = The original index #闭合函数, outsourced
# func= the most primitive index
def wrapper (): #嵌套定义的函数
Start_time=time.time ()
Func ()
Stop_time=time.time ()
Print (Stop_time-start_time)
Return wrapper
Index=outter (Index) # new Index=wrapper #将返回值wrapper赋予index
Index () #wrapper () #等于weapper函数
Second, no reference decorator upgrade version
Import time
def index ():
Time.sleep (1)
Print (' Welcome to index page ')
Return 122
def home (name):
Time.sleep (2)
Print (' Welcome%s to home page '%name)
#============== Decorator
def Timmer (func): #外包
#func = The original home
def wrapper (*args,**kwargs): #嵌套函数, give formal parameter *args,**kwargs to solve the problem of calling function self-parameters
Start_time=time.time ()
Res=func (*args,**kwargs) #调用最原始的home, assigning a value to res to leave back
Stop_time=time.time ()
Print (Stop_time-start_time)
return res #对应带返回值的函数处理
Return wrapper
Index=timmer (Index) # new Index=wrapper
Home=timmer (home) #新的home =wrapper
# ==========================================
Home (name= ' Egon ') #wrapper (' Egon ')
Index () #wrapper ()
#无参装饰器模板
def outer (func):
def inner (*args,**kwargs):
Res=func (*args,**kwargs)
return res
return inner
Third, decorator syntax
The keyword @,@ followed by the adorner function name, just below the function needed to use the adorner, @ must be a separate line
Import time
def Timmer (func):
def wrapper (*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 ')
Return 122
@timmer # Home=timmer (Home)
def home (name):
Time.sleep (2)
Print (' Welcome%s to home page '%name)
# index ()
Home (' Egon ')
Four, overlay a plurality of decorative device
Import time
current_user={#字典用于存用户名
' username ': None,
# ' Login_time ': None
}
def auth (func): #注册装饰器
# Func=index
def wrapper (*args,**kwargs):
If current_user[' username ']:
Print (' already logged in ')
Res=func (*args,**kwargs)
return res
Uname=input (' User name >>: '). Strip ()
Pwd=input (' Password >>: '). Strip ()
if uname = = ' Egon ' and pwd = = ' 123 ':
Print (' Login successful ')
current_user[' username ']=uname
Res=func (*args,**kwargs)
return res
Else
Print (' User name or password error ')
Return wrapper
def Timmer (func): #时间装饰器
def wrapper (*args,**kwargs):
Start_time=time.time ()
Res=func (*args,**kwargs)
Stop_time=time.time ()
Print (Stop_time-start_time)
return res
Return wrapper
@timmer # Timmer Statistics is the execution time of Auth+index
@auth
def index ():
Time.sleep (1)
Print (' Welcome to index page ')
Return 122
Index ()
Two kinds of adorner overlay use (red character), Timmer for the next only to count the run time of index, put above statistics is auth+index execution time
Five, has the parameter adorner
Import time
current_user={
' username ': None,
# ' Login_time ': None
}
def auth (engine): #再在外面定义一个有参函数用于传值, three-layer decorator
# engine= ' file '
def auth2 (func): #第二层包第一层
# Func=index
def wrapper (*args,**kwargs): #第一层
if engine = = ' file ':
If current_user[' username ']:
Print (' already logged in ')
Res=func (*args,**kwargs)
return res
Uname=input (' User name >>: '). Strip ()
Pwd=input (' Password >>: '). Strip ()
if uname = = ' Egon ' and pwd = = ' 123 ':
Print (' Login successful ')
current_user[' username ']=uname
Res=func (*args,**kwargs)
return res
Else
Print (' User name or password error ')
elif engine = = ' MySQL ':
Print (' MYQL-based authentication ')
elif engine = = ' LDAP ':
Print (' LDAP-based authentication ')
Return wrapper
Return auth2 #返回值为auth2
#用法 @ The third-level function name plus arguments, because execution to this code will run, the return value is auth2, is equal to the execution of the @auth2, the successful assignment index
@auth (' LDAP ') # @auth2 #index =auth2 (index) #index =wrapper
def index ():
Time.sleep (1)
Print (' Welcome to index page ')
Return 122
Index () # wrapper ()
Python tour. Chapter III. FUNCTION 3.29