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

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之函数嵌套与闭包的更多相关文章

  1. python基础—函数嵌套与闭包

    python基础-函数嵌套与闭包 1.名称空间与作用域 1 名称空间分为: 1 内置名称空间   内置在解释器中的名称 2 全局名称空间   顶头写的名称 3 局部名称空间 2 找一个名称的查找顺序: ...

  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 ...

  3. python中函数嵌套、函数作为变量以及闭包的原理

    嵌套函数: python允许创建嵌套函数.也就是说我们可以在函数里面定义函数,而且现有的作用域和变量生存周期依旧不变. 例子: #encoding=utf-8 def outer():    name ...

  4. Python开发——函数【装饰器、高阶函数、函数嵌套、闭包】

    装饰器 装饰器本质就是函数,为其他函数添加附加功能. 原则: 不修改被修饰函数的源代码 不修改被修饰函数的调用方法 装饰器知识储备:装饰器 = 高阶函数 + 函数嵌套 + 闭包 案例:求函数运行时间! ...

  5. python全栈开发_day11_作用域,函数嵌套和闭包

    一:作用域 1)什么是作用域 作用域是规定一个变量可以作用的范围,运行和销毁的范围 2)作用域的分类 1.内置作用域built_in:随着解释器的运行而产生,解释器运行的终止而销毁. 2.全局作用域g ...

  6. python之函数嵌套

    python很多特性与JavaScript是相似甚至相同的: 1. 无类型 2. 函数亦对象 .... 自然: python也允许函数嵌套, 这与JavaScript中函数闭包的作用一样....

  7. 10 - 函数嵌套-作用域-闭包-LEGB-函数销毁

    目录 1 函数嵌套 2 作用域 2.1 global关键字 3 闭包 3.1 nonlocal关键字 4 默认值的作用域 5 变量名解析原则LEGB 6 函数的销毁 1 函数嵌套         一个 ...

  8. Python虚拟机函数机制之闭包和装饰器(七)

    函数中局部变量的访问 在完成了对函数参数的剖析后,我们再来看看,在Python中,函数的局部变量时如何实现的.前面提到过,函数参数也是一种局部变量.所以,其实局部变量的实现机制与函数参数的实现机制是完 ...

  9. js中的函数嵌套和闭包

    小编已经有一段时间没有更新文章了,最近一直在考虑接下来要更新什么内容.接下来,小编会围绕以下三个方面更新文章.实际项目中遇到的问题和解决方案.Vue源码解析.代码重构.关于数据可视化.小编也会按照这个 ...

随机推荐

  1. MySQL中character set与collation的理解(转)

    character set和collation的是什么? character set即字符集 我们常看到的UTF-8.GB2312.GB18030都是相互独立的character set.即对Unic ...

  2. JUC集合之 JUC中的集合类

    Java集合包 在"Java 集合系列01之 总体框架"中,介绍java集合的架构.主体内容包括Collection集合和Map类:而Collection集合又可以划分为List( ...

  3. O(n)线性空间的迷宫生成算法

    之前所有的迷宫生成算法,空间都是O(mn),时间同样是O(mn),时间上已经不可能更优化, 于是,我就从空间优化上着手,研究一个仅用O(n)空间的生成算法. 我初步的想法是,每次生成一行,生成后立即输 ...

  4. 设置新时间校正服务器NTP SERVER

    时间校正服务器IP : 10.*.*.* 适用系统:windows server 2008/windows 7 net stop w32time net start w32time w32tm /qu ...

  5. RFID:ISO14443、15693、18000体系分析

    射频标签的通信标准是标签芯片设计的依据,目前国际上与RFID相关的通信标准主要有:ISO/IEC 18000标准(包括7个部分,涉及125KHz, 13.56MHz, 433MHz, 860-960M ...

  6. bzoj 4929: 第三题

    Description 给定n,b,c,d,e以及A0,A1,···,An−1,定义 xk=b×c^4k+d×c^2k+e f(x)=Sigma(Aix^i),0<=i<=n-1 请你求出 ...

  7. spring boot学习(7) SpringBoot 之表单验证

    第一节:SpringBoot 之表单验证@Valid 是spring-data-jpa的功能:   下面是添加学生的信息例子,要求姓名不能为空,年龄大于18岁.   贴下代码吧: Student实体: ...

  8. 学习笔记之JSON

    JSON https://www.json.org/ JSON (JavaScript Object Notation) is a lightweight data-interchange forma ...

  9. centos 安装LAMP环境后装phpmyadmin

    首先在CentOS 上安装EPEL 要想安装EPEL,我们先要下载EPEL的rpm安装包. 1. 确认你的CentOS 的版本 首先通过以下命令确认你的CentOS 版本 $ cat /etc/Red ...

  10. 检测2个公网IP的GRE隧道是否通的方法,使用PPTP拨号检测。

    检测2个公网IP的GRE隧道是否通的方法,使用PPTP拨号检测. 因为PPTP是建立在GRE隧道基础上的. PPTP 防火墙开放 TCP 1723防火墙开放 IP protocol 47,即GRENA ...