闭包,装饰器学习
高阶函数
可以接受一个函数作为参数的函数称为高阶函数
def add(a,b):
return a+b
def behave(opt,opt_a,opt_b):
return opt(opt_a,opt_b)
print(behave(add,1,3))
闭包
在外层函数将内层函数名返回出去
闭包特点:
正常情况下,函数返回值以后,函数内局部变量所占有的空间都会被释放出来
但是,在闭包操作中,内层函数返回到外部时,内层函数所需的变量(包括所需要的外层函数中的变量)都会被保留出来,
调用该函数时,优先使用这一层作用域
def wrapper():
def inner():
print("hi")
return inner
man = wrapper()
man()
装饰器
装饰器作用
在不改变源代码和调用方式情况下,给函数添加新功能
需要用到闭包和高阶函数知识
装饰器创建
def login(func):
def inner(*argc,**argv):
#简单的登录验证程序
username = input("name>>:")
password = input("psword>>:")
if username == "xu" and password == "123":
print("欢迎登录")
func(*argc,**argv)
else:
print("登录失败")
return inner
@login
def index():
print("This is homepage")
index()
1.先写一个闭包
1)外层函数作用,就是将接受的函数参数给内层函数 def login(func):
2)内层函数经过包装,添加一些新功能,再由外层函数将其返回 def inner(*argc,**argv):
内存函数的传入参数,是为了将inner所接收的参数传入func(*argc,**argv)
被接受的参数
2.外层函数返回的是一个内层函数的函数名,这样就导致,第一次调用外层函数时候,不会执行内层函数。
相对于login2,
func1 = login(index) #-->返回inner函数名(内层函数地址)
func1相当于inner函数,相当于
def func1(*argc,**argv): #--》相当于将inner函数指针赋值给func1
#简单的登录验证程序
username = input("name>>:")
password = input("psword>>:")
if username == "xu" and password == "123":
print("欢迎登录")
index(*argc,**argv) #---》将外层函数的参数赋值给内层函数,现在的内层函数就变成这样
else:
print("登录失败")
return inner
func2 = login2(index) #-->执行login2函数,返回是None(因为login2没有返回值)
fun2为none
3.将内层函数赋值给index变量
index = login(index) #--》原来index变量指向print("This is homepage")函数,现在将这个变量指向inner函数
index() #-->现在的index就相当于内层函数
以上两步等价于
@login
def index():
print("This is homepage")
多个装饰器
def hello(func):
def inner(*argc,**argv):
print("hello,open")
func(*argc,**argv)
return inner
@hello
@login
def index():
print("This is homepage")
index()
返回
hello,open
name>>:xu
psword>>:123
欢迎登录
This is homepage
上面
@hello
@login
def index():
print("This is homepage")
等价于
def index():
print("This is homepage")
index = login(index)
index = hello(index)
带参数的装饰器
def login(auth_type):
def auth(func):
def inner(*argc,**argv):
#简单的登录验证程序
username = input("name>>:")
password = input("psword>>:")
if auth_type == "qq":
print("qq登录")
if username == "xu" and password == "123":
print("欢迎登录")
func(*argc,**argv)
else:
print("登录失败")
else:
print("不支持其他登录模式")
return inner
return auth
@login('qq')
def index1():
print("This is homepage1")
@login('weibo')
def index2():
print("This is homepage2")
print(index1())
print(index2())
结果
name>>:xu
psword>>:123
qq登录
欢迎登录
This is homepage1
None
name>>:xu
psword>>:123
不支持其他登录模式
None
相当于嵌套两次,相对于对装饰器再增强一次,强中强