The role of adorners: To add functionality without changing the source code and the calling method
(i) the base adorner (only implemented as function add function)
Feature implementation:
Add the ability to calculate run time for the original function
" "High -order function + nested function = Adorner Adorner principle: (1) cannot change the source code of the decorated function (2) cannot change the method of calling the decorated function" "Import TimedefTimer (func):defFunc_deco (*args,**Kwargs): Start_time=time.time () func (*args,**Kwargs) Run_time=time.time ()-start_timePrint("function run time is%s"%run_time)returnFunc_deco#returns the memory address of the function run@timerdefFun_te (name,age): Time.sleep (1) Print(name)Print(age) Fun_te ('Lihanyu', 18)
The test results are as follows:
(ii) Adorner climax version
The scenario is implemented as follows: During the login process of the website, part is local log on, part is LDAP login, after the login method is determined, the user login function is realized.
Importtimeuser,pwd=('Lihanyu',' the')defout (auth_type):defAuth (func):defWapper (*args,**kwargs):#can implement arbitrary number of parameters ifauth_type=='Local': Username=input ("Username:") Password=input ("Password:") ifUsername==user andpassword==pwd:Print("Validation Successful") Res=func (*args,**Kwargs)returnRes#Returns the return value of the running function, which is the return value of home () Else: Print("user name or password input error") elifauth_type=='LDAP': Print("I don't know ... ") Else: Print("no such sign-in method") returnWapperreturnAuthdefindex ():Print("Welcome to Index") @out (Auth_type='Local')defHome ():Print('Welcome to Home Page') return "From home"@out (Auth_type='LDAP')defBBS ():Print("Welcome to BBS") index ()Print(Home ()) BBS ()
The test results are as follows:
Welcome to the Great God test, correct me, thank you!
Python's Decorator