python之函数嵌套与闭包

一:函数的嵌套:在函数内部在定义一个函数,一层套一层

def father(name):
    print("from father %s" %name)
    def son():
       print("我的爸爸是%s" %name)
    son()
father("wangyue")

  

二:写一个装饰器的框架

写一个装饰器的框架,满足高阶函数,满足闭包嵌套
# def timer(func):
#     def wrapper():
#         print(func)
#         func()#本层没有func,只能从上层找,所以此时是执行的test这个函数
#     return wrapper

  

# def test():
#     print("执行完毕")
# res = timer(test)#返回的是wrapper的地址
# res()#执行的额是wrapper()

  

三:函数闭包加上返回值:

import time
def timer(func):
    def wrapper():
        start_time = time.time()
        res=func()#就是在运行test
        stop_time = time.time()
        print("运行时间是%s" %(stop_time-start_time))
        return res
    return wrapper

@timer #test = timer(test)
def test():
    print("执行完毕")
    return "ddd"
res = test()
print(res)

四:函数闭包加上参数:

就上个例子来说,加上name和age两个参数

#函数闭包加上参数
import time
def timer(func):
    def wrapper(name,age):
        start_time = time.time()
        res=func(name,age)#就是在运行test
        stop_time = time.time()
        print("运行时间是%s" %(stop_time-start_time))
        return res
    return wrapper

@timer #test = timer(test)
def test(name,age):
    print("执行完毕")
    return "ddd"
res = test("wanggyue",25)
print(res)#执行test就相当于执行timer的返回值

  

#函数闭包加上参数
import time
def timer(func):
    def wrapper(*args,**kwargs):#被修饰的函数参数是不固定的,所以不能写死参数,所以修该装饰器改为*args接受的元祖的格式,**kwargs接受的是字典的格式
        start_time = time.time()
        res=func(*args,**kwargs)#就是在运行test
        stop_time = time.time()
        print("运行时间是%s" %(stop_time-start_time))
        return res
    return wrapper

@timer #test = timer(test)
def test1(name,age):
    print("test函数执行完毕,名字是【%s】 年龄是【%s】" %(name,age))
    return "这是test的返回值"

@timer #相当于test = timer(test1)
def test1(name,age,gender):#被修饰的函数参数是不固定的,所以不能写死参数,所以修该装饰器
    print("test1函数执行完毕,名字是【%s】 年龄是【%s】 性别是【%s】" %(name,age,gender))
    return "这是test1的返回值"
test1("wangyue",25,"女")

 五:函数闭包之解压序列

#解压序列
l=[10,3,4,6,7,8,3,90,6,7,78]
#实现解压方式取开头和结尾的值
a,*_,c = l  #a代表第一个,*_所有中间,c是末尾
a,*_,c,d=l #取第一个值和倒数第一和第二个值
print(a)

python实现值的互换

#实现a,b值互换,正常写法
c=a
a=b
b=c
print(a)
print(b)
#另一种写法
f1=1
f2=2
f1,f2 = f2,f1
print(f1)
print(f2)

六:函数闭包为函数加上认证功能,联系京东商城每个模块加上用户名和密码验证功能

#为一下函数加上验证功能,写装饰器
def auth_func(func):
    def wrapper(*args,**kwargs):
        #此处输入验证功能
        username= input("用户名:".strip())
        password = input("密码:".strip())
        if username == "you"and password =="123":
           res = func(*args, **kwargs)
           print("返回值%s" %(res))
           return res
        else:
            print("输入错误")
    return wrapper
# 模拟京东商城后台
@auth_func
def index():
  print("欢迎来到京东主页")
  pass

@auth_func
def home(name):  # 京东的主页
    print("欢迎回家%s" %(name))

@auth_func
def shopping_car(name):  # 京东的购物车
    print("购物车里有[%s,%s]" %("奶茶","妹妹"))

# @auth_func
def order():  # 京东的订单
    pass


# 给每个模块加上一个验证功能
def yanzheng():
   pass

index()
home('产品经理')
shopping_car("产品经理")

七:函数闭包模拟session功能:

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

#为一下函数加上验证功能,写装饰器
def auth_func(func):
    def wrapper(*args,**kwargs):
        #此处输入验证功能
        if cirrentuserdic["username"] and cirrentuserdic["login"]:
            res = func(*args, **kwargs)
            return res
        username1= input("用户名:".strip())
        password1 = input("密码:".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('用户名或者密码错误')
    return wrapper
# 模拟京东商城后台
@auth_func
def index():
  print("欢迎来到京东主页")
  pass

@auth_func
def home(name):  # 京东的主页
    print("欢迎回家%s" %(name))

@auth_func
def shopping_car(name):  # 京东的购物车
    print("购物车里有[%s,%s]" %("奶茶","妹妹"))


print('before-->',cirrentuserdic)
index()
print('after--->',cirrentuserdic)
home('产品经理')

接下来思考如何给装饰器加上参数(用的比较少)

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

#接下来增加验证功能,加一个装饰器实现这个功能
def auth(auth_type='filedb'):
  def auth_func(func):
    def wrapper(*argc,**kwargs):
        print("类型--",auth_type)
        if auth_type=='filedb':
        #添加验证逻辑
            if cirrentuserdic["username"] and cirrentuserdic["login"]:
                res = func(*argc,**kwargs)
                return res
            username=input("用户名:".strip())
            password = input("密码:".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("输入错误")
        elif auth_type=='ldap':
            print("真会玩")

    return wrapper
  return auth_func

@auth(auth_type='filedb')#auth_func=auth(auth_type='filedb',auth_func附加了auth_type
def index():
    print("欢迎来到京东")
@auth(auth_type='ldap')
def home():
    print("欢迎进入京东主页")
@auth
def order():
    print("京东订单")

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

  

猜你喜欢

转载自www.cnblogs.com/wangyue0925/p/8973682.html