One. Adorner (a very important content)
Definition: The essence is a function, (decorating other functions) is to add other functions for other functions
Note: A. Cannot modify the source code of the decorated function,
B. You cannot modify the calling method of the decorated function.
Add:
A. The function is "variable" and assigns the function body to the function name.
B. Higher-order functions + nested functions >>>> decorators
C. Higher order functions: pass a function name as an argument to another function (without modifying the source code of the decorated function);
The return value contains the function name (without modifying the way the decorated function is called).
#一个函数名当做实参传给另一个函数
Import TimedefBar (): Time.sleep (3) Print('In the bar')defTest1 (func): Start_time=time.time () func ()#Run BarStop_time =time.time ()Print("The func run time is%s"% (Stop_time-start_time))#run time equals end time minus start timeTest1 (BAR)
Note: I don't understand this (hahaha)
# The return value contains the function name
Import timedef Bar (): time.sleep (3) print(' In the bar ' )def Test2 (func): print(func) return func#print (Test2 (bar))bar = test2 (bar) bar ()
d. Nested functions
A function is nested, and a function is declared inside the function, not a call to the
def foo (): Print ("in thefoo") def Bar (): Print ("intne bar") #函数的嵌套, declare a function inside the function, instead of calling Bar () foo ()
#局部变量与全局变量的访问次序:
x = 0def Grandpa (): = 1 def dad (): x=2 def son (): x=3 Print (x) son () dad () Grandpa ()
Run Result: 3
1 Import Time2USER,PASSWD ="Xiaolaizi","abc123"3 #Decorative Device4 defAuth (func):5 defWrapper (*args,**Kwargs):6Username = input ("Username:"). Strip ()#strip go to space7Password = input ("Password:"). Strip ()8 9 ifuser = = Username andpasswd = =Password:Ten Print("\033[32;1muser has passed authentication\033[0m") Oneres = func (*args,**Kwargs) A Print(20*'*') - returnRes - Else: theExit"\033[31;1muser have not passed authentication\033[0m") - returnwrapper - defIndex ():#Define a home page - Print("Welcome to Index page") +@auth#Local authentication @auth (auth_type = "local") - defHome ():#Define a landing page + Print("Welcome to Home Page") A return "From home" at@auth#Remote Authentication @auth (Auth_type = "LDAP") - defBBS ():#Define a forum area page - Print("Welcome to BBS page") - - index () - Print(Home ()) in #Home () -BBS ()
View Code
Python Basics (iv)