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()
python之函数嵌套与闭包的更多相关文章
- python基础—函数嵌套与闭包
python基础-函数嵌套与闭包 1.名称空间与作用域 1 名称空间分为: 1 内置名称空间 内置在解释器中的名称 2 全局名称空间 顶头写的名称 3 局部名称空间 2 找一个名称的查找顺序: ...
- 《Python》 函数嵌套、闭包和迭代器
一.函数的嵌套: 1.函数的嵌套调用 def max2(x,y): m = x if x>y else y return m def max4(a,b,c,d): res1 = max2(a,b ...
- python中函数嵌套、函数作为变量以及闭包的原理
嵌套函数: python允许创建嵌套函数.也就是说我们可以在函数里面定义函数,而且现有的作用域和变量生存周期依旧不变. 例子: #encoding=utf-8 def outer(): name ...
- Python开发——函数【装饰器、高阶函数、函数嵌套、闭包】
装饰器 装饰器本质就是函数,为其他函数添加附加功能. 原则: 不修改被修饰函数的源代码 不修改被修饰函数的调用方法 装饰器知识储备:装饰器 = 高阶函数 + 函数嵌套 + 闭包 案例:求函数运行时间! ...
- python全栈开发_day11_作用域,函数嵌套和闭包
一:作用域 1)什么是作用域 作用域是规定一个变量可以作用的范围,运行和销毁的范围 2)作用域的分类 1.内置作用域built_in:随着解释器的运行而产生,解释器运行的终止而销毁. 2.全局作用域g ...
- python之函数嵌套
python很多特性与JavaScript是相似甚至相同的: 1. 无类型 2. 函数亦对象 .... 自然: python也允许函数嵌套, 这与JavaScript中函数闭包的作用一样....
- 10 - 函数嵌套-作用域-闭包-LEGB-函数销毁
目录 1 函数嵌套 2 作用域 2.1 global关键字 3 闭包 3.1 nonlocal关键字 4 默认值的作用域 5 变量名解析原则LEGB 6 函数的销毁 1 函数嵌套 一个 ...
- Python虚拟机函数机制之闭包和装饰器(七)
函数中局部变量的访问 在完成了对函数参数的剖析后,我们再来看看,在Python中,函数的局部变量时如何实现的.前面提到过,函数参数也是一种局部变量.所以,其实局部变量的实现机制与函数参数的实现机制是完 ...
- js中的函数嵌套和闭包
小编已经有一段时间没有更新文章了,最近一直在考虑接下来要更新什么内容.接下来,小编会围绕以下三个方面更新文章.实际项目中遇到的问题和解决方案.Vue源码解析.代码重构.关于数据可视化.小编也会按照这个 ...
随机推荐
- async(await)知识点
async 函数是 Generator 函数的语法糖. async 函数对 Generator 函数的改进体现在: async 内置执行器. Generator 函数的执行必须靠执行器,需要调用 ne ...
- Microsoft Dynamics CRM 4.0 Plugin 取值,赋值,查询
DynamicEntity postImageEntity = (DynamicEntity)context.PostEntityImages["PostImage"]; if ( ...
- Django QuerySet和中介模型
笔记如下 一.QuerySet QuerySet是什么? 类似列表里边存着对象 只和ORM有关系 from app01.models import Book def qDemo(request): b ...
- Mycat 数据库分库分表中间件
http://www.mycat.io/ Mycat 国内最活跃的.性能最好的开源数据库中间件! 我们致力于开发高性能的开源中间件而努力! 实体书Mycat权威指南 »开源投票支持Mycat下载 »s ...
- java 复制对象 (克隆接口 与 序列化)
关于java对象复制我们在编码过程经常会碰到将一个对象传递给另一个对象,java中对于基本型变量采用的是值传递,而对于对象比如bean传递时采用的是应用传递也就是地址传递,而很多时候对于对象传递我们也 ...
- BASIC-23_蓝桥杯_芯片测试
思路: 1.当测试与被测试的芯片全部可以互相测试时,为好芯片; 示例代码: #include <stdio.h>#define N 20 int main(void){ int n = 0 ...
- 【FusionCharts学习-3】显示中国地图
概述 使用FusionCharts显示中国地图 资源获取 地图下载地址:http://www.fusioncharts.com/download/maps/definition/ 将下载的地图拷贝 ...
- [原]DataGridView 回车不换行代码 AND 编辑时的字符控制
// 让 dataGridView1 在遇到回车时不响应 protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { ...
- shell 4注释
单行注释 每一行加一个#号. #shell #!/bin/sh echo "#" #轻轻的我走了 #正如我轻轻的来 #我挥一挥衣袖 #不带走一片云彩 echo "#&qu ...
- div+Css绝对定位(absolute)和相对定位(relative)的总结
1.没有外Div的情况下 设置绝对定位(absolute)和相对定位(relative)是没有区别的 2.相对定位占位置 而绝对定位不占位置 会漂浮在别的Div之上 3.若父Div没有设置定位,子Di ...