Start learning the second module:
Adorner:
Describe:
Adorner principle:
1. Cannot modify the source code of the decorated function
2, can not modify the decoration of the function of the caller test
To implement the adorner:
Higher order function + nested function = Adorner
Higher order functions:
Type I: a function that functions as an argument, which can be called a higher order function
1 def fun_1 (fun_2): # fun_1 is a higher order function 2 Span style= "COLOR: #0000ff" >print ( " 1 " ) 3 fun_2 () 4 5 def Fun_2 (): 6 print ( 2 " ) 7 8 fun_1 (fun_2)
Type II: The function that contains the function name in the return value, also called the higher order function
def fun_3 (fun): # fun_3 is a higher-order function print (" 3 " ) return fun def Fun_4 (): print (" 4 " ) # fun_3 (fun_4) () #返回值可以直接运行 fun=fun_3 (fun_4) # You can assign the return value to a variable Fun () # can call function
Nested functions:
Define a new function in the function called a nested function
1 def fun_5 ():#fun_5 for nested functions 2 print('5' )3 def Fun_5_1 ():4 print(' 5.1')5 6 fun_5 ()
The simplest of decorations:
1 defFun_2 (Fun):#functions passed into fun_12 deffunction ():3 4 Fun ()5 Print('In the fun_2 ...')#Add new Content6 7 returnfunction8 9@fun_2#Decorative fun_! Equivalent to Fun_1=fun_2 (fun_1)Ten deffun_1 (): One Print("In the fun_1 ....") A - -Fun_1 ()
Decorator: Analogue Login Certification
1 #Analog Website Login access authentication2 #3Name='ABC'4password='123'5 defCerti (model):#Decorative Device6 defOutr (Fun):#Adorner plus parameter requires extra nesting7 defLogin (*args,**kwargs):#to be compatible with various function parameters, add *args,**kwargs invariant parameters8 ifmodel=='Password':9 Print('This is password certification .')Tenuser_name = input ('User name:'). Strip () OnePaswd=input ('Password:'). Strip () A ifUser_name==name andpaswd==Password: - Print('through Certification') - returnFun (*args,**Kwargs) the Else: - Print('user or password error, exit') - exit () - elifmodel=='Lamp': + Print('This is the lamp certification') - returnFun (*args,**Kwargs) + Else: A Print('Authentication Error') at returnLogin - returnOutr - - - defindxe (): - Print('Welcome to Homepage') in -@certi (model='Password') to defUser (): + Print('Welcome to the user page:') - the@certi (model='Lamp') * defBBS (name): $ Print('Welcome to%s Landing Forum !'%name)Panax Notoginseng - Indxe () the User () +BBS (name='YJJ')
Python 11th day