Python装饰器的理解


'''
复习 装饰器的本质就是函数:装饰其他函数的函数
原则:
1、不能改变被装饰函数的代码
2、不能改变被装饰函数的调用方式

知识储备:
1、函数即变量
2、高阶函数
什么是高阶函数?
1、当函数名作为变量传递给另外一个函数时 就是高阶函数
2、当函数的返回值是函数名时也是高阶函数
3、函数嵌套
函数中定义另外一个函数

装饰器使用了:高阶函数 和 函数嵌套 两个知识点
重要的是装饰器的语法糖
相当于 home = auth(home) 这里是将auth函数中的wrapper函数名传递给了home 再调用home()时就是调用wrapper()
这个才是装饰器的重点
场景
1、当被修饰的函数含有形参时应该怎么写装饰器函数?
2、当装饰器函数有形参时应该怎么写?
3、当被装饰的函数有返回值时应该怎么写?
4、无参数的装饰器怎么写
以上在装饰器的例子中均有解释

当定义一个函数时
def foo()
pass
foo是函数名 是函数的内存地址
foo()是运行函数 执行函数的调用
'''

'''疑问:当装饰器带有参数的时候该怎么写呢?在装饰器函数外再加一层传递参数即可

'''
import time
user,passwd = "alex","abc123"

def auth(auth_type):
print("in the func auth auth_type %s"%auth_type)
def outer_wrapper(func):
def wrapper(*args,**kwargs):
print("in the func wrapper")
username = input("user name:").strip()
password = input("password:").strip()
#当输入的用户名和密码正确时才执行被装饰的函数
if user==username and password == passwd:
if auth_type == "local":
print("local")
res = func(*args,**kwargs) # 如果function有返回值 需要将值返回一下
return res
elif auth_type == "ldap":
print("ldap")
func(*args,kwargs)
else:
print("please input correct user name and passwd!")

return wrapper # 将函数名返回
return outer_wrapper


'''写一个登陆验证的装饰器对这三个函数进行修饰'''


@auth(auth_type = "local") # 相当于 home = auth(home)所以这里会执行auth(home)函数,执行完以后将定义的wrapper函数名返回
def home():
print("welcome to home page")
return "from func home"


@auth(auth_type = "ldap")
def index():
print("welcome to index")


def bbs():
print("welcome to bbs")


print(home())
index()
bbs()