Function nesting and closure in python

One: Nesting of functions: define a function inside the function, layer by layer

def father(name):
    print("from father %s" %name)
    def son():
       print("My dad is %s" %name)
    son()
father("wangyue")

  

Two: write a framework for decorators

Write a decorator framework that satisfies higher-order functions and satisfies closure nesting
# def timer(func):
#     def wrapper():
#         print(func)
# func()# There is no func in this layer, it can only be found from the upper layer, so this time is the function test that is executed
#     return wrapper

  

# def test():
# print("Executed")
# res = timer(test)# returns the address of the wrapper
# res()# The amount of execution is wrapper()

  

Three: function closure plus return value:

import time
def timer(func):
    def wrapper():
        start_time = time.time()
        res=func()# is running test
        stop_time = time.time()
        print("The running time is %s" %(stop_time-start_time))
        return res
    return wrapper

@timer #test = timer (test)
def test():
    print("Executed")
    return "ddd"
res = test()
print(res)

Four: function closure plus parameters:

In the previous example, add the two parameters name and age

#Function closure plus parameters
import time
def timer(func):
    def wrapper(name,age):
        start_time = time.time()
        res=func(name,age)# is running test
        stop_time = time.time()
        print("The running time is %s" %(stop_time-start_time))
        return res
    return wrapper

@timer #test = timer (test)
def test(name,age):
    print("Executed")
    return "ddd"
res = test("wanggyue",25)
print(res)#Executing test is equivalent to executing the return value of timer

  

#Function closure plus parameters
import time
def timer(func):
    def wrapper(*args,**kwargs):#The parameters of the function to be decorated are not fixed, so the parameters cannot be written dead, so the decorator is changed to the format of the ancestor accepted by *args, and **kwargs is accepted by the dictionary format
        start_time = time.time()
        res=func(*args,**kwargs)# is running test
        stop_time = time.time()
        print("The running time is %s" %(stop_time-start_time))
        return res
    return wrapper

@timer #test = timer (test)
def test1(name,age):
    print("The test function is executed, the name is [%s] and the age is [%s]" %(name,age))
    return "This is the return value of test"

@timer #equivalent to test = timer(test1)
def test1(name,age,gender):#The parameters of the decorated function are not fixed, so the parameters cannot be written dead, so repair the decorator
    print("The test1 function is executed, the name is [%s], the age is [%s], and the gender is [%s]" %(name,age,gender))
    return "This is the return value of test1"
test1("wangyue",25,"女")

 Five: Decompression sequence of function closure

#decompression sequence
l=[10,3,4,6,7,8,3,90,6,7,78]
# Implement the decompression method to get the values ​​at the beginning and end
a,*_,c = l #a represents the first, *_ all the middle, c is the end
a,*_,c,d=l #Take the first value and the penultimate and second value
print(a)

Python realizes the exchange of values

#Realize a, b value exchange, normal writing
c=a
a=b
b=c
print(a)
print(b)
#another way of writing
f1 = 1
f2=2
f1,f2 = f2,f1
print(f1)
print(f2)

Six: The function closure adds the authentication function to the function, contact each module of Jingdong Mall and add the user name and password verification function

#Add validation function to the following function, write decorator
def auth_func(func):
    def wrapper(*args,**kwargs):
        #Enter the verification function here
        username= input("Username: ".strip())
        password = input("Password: ".strip())
        if username == "you"and password =="123":
           res = func(*args, **kwargs)
           print("Return value %s" %(res))
           return res
        else:
            print("input error")
    return wrapper
# Simulate the backstage of Jingdong Mall
@auth_func
def index():
  print("Welcome to JD.com homepage")
  pass

@auth_func
def home(name): # Jingdong's homepage
    print("Welcome home %s" %(name))

@auth_func
def shopping_car(name): # Jingdong's shopping cart
    print("There are [%s,%s] in the shopping cart" %("Milk tea","Sister"))

# @auth_func
def order(): # Jingdong's order
    pass


# Add a validation function to each module
def yanzheng():
   pass

index()
home('Product Manager')
shopping_car("Product Manager")

Seven: The function closure simulates the session function:

cirrentuserdic ={"username":None ,"login":False}
user_list = [{"username":"wangyue" ,"password":"123"},
             {"username":"songyang","password":"123"},
             {"username":"zhaozhen","password":"123"},
             {"username":"wangebiebi","password":"123"}]

#Add validation function to the following function, write decorator
def auth_func(func):
    def wrapper(*args,**kwargs):
        #Enter the verification function here
        if cirrentuserdic["username"] and cirrentuserdic["login"]:
            res = func(*args, **kwargs)
            return res
        username1= input("Username: ".strip())
        password1 = input("Password: ".strip())
        for userdic1 in  user_list:
            if username1==userdic1["username"] and password1==userdic1["password"]:
                cirrentuserdic["username"] = username1
                cirrentuserdic["login"] = True
                res = func(*args, **kwargs)
                return res
        else:
                print('Username or password is incorrect')
    return wrapper
# Simulate the backstage of Jingdong Mall
@auth_func
def index():
  print("Welcome to JD.com homepage")
  pass

@auth_func
def home(name): # Jingdong's homepage
    print("Welcome home %s" %(name))

@auth_func
def shopping_car(name): # Jingdong's shopping cart
    print("There are [%s,%s] in the shopping cart" %("Milk tea","Sister"))


print('before-->',cirrentuserdic)
index()
print('after--->',cirrentuserdic)
home('Product Manager')

Next, think about how to add parameters to the decorator (less used)

cirrentuserdic ={"username":None ,"login":False}
user_list = [{"username":"wangyue" ,"password":"123"},
             {"username":"songyang","password":"123"},
             {"username":"zhaozhen","password":"123"},
             {"username":"wangebiebi","password":"123"}]

#Next, add the verification function and add a decorator to implement this function
def auth(auth_type='filedb'):
  def auth_func(func):
    def wrapper(*argc,**kwargs):
        print("Type --",auth_type)
        if auth_type=='filedb':
        #Add validation logic
            if cirrentuserdic["username"] and cirrentuserdic["login"]:
                res = func(*argc,**kwargs)
                return res
            username=input("Username: ".strip())
            password = input("Password: ".strip())
            for user_dic in  user_list:
              if username==user_dic["username"] and password == user_dic["password"]:
                cirrentuserdic["username"]=username
                cirrentuserdic["login"] = True
                res = func(*argc, **kwargs)
                return res
            else:
                print("input error")
        elif auth_type=='ldap':
            print("Really play")

    return wrapper
  return auth_func

@auth(auth_type='filedb')#auth_func=auth(auth_type='filedb',auth_func附加了auth_type
def index():
    print("Welcome to Jingdong")
@auth(auth_type='ldap')
def home():
    print("Welcome to JD.com homepage")
@auth
def order():
    print("Jingdong order")

print("before--",cirrentuserdic)
index()
print("after--",cirrentuserdic)
home()

  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325084065&siteId=291194637