# def f1(): # print(123) # def f1(): # print(456) # f1() 结果 456 # def f1(): # print('123') # def f2(xxx): # xxx() 结果123 # f2(f1)
# 定义函数,为调用,函数内部不执行 # 函数名 > 代指函数 ----------------------------------------------------------- def outer(func): def inner(*args, **kwargs): inner代表包装后的函数 print('before') r = func(*args, **kwargs) func()代表原函数 print('after') return r return inner # @ + 函数名 # 功能: # 1. 自动执行outer函数并且将其下面的函数名f1当作参数传递 # 2. 将outer函数的返回值,重复赋值给 f1 @outer def f1(arg): print(arg) return "132" @outer def f2(a1, a2): print("F2") @outer def f3(): print("F3") -------------------------------------------------------------- 简单装饰器:
LOGIN_USER = {"is_login": False } def outer(func): def inner(*args, **kwargs): if LOGIN_USER['is_login']: r = func() return r else: print("请登录") return inner @outer #验证登录(装饰器) def manager(): print("欢迎%s登录" % LOGIN_USER['current_user']) def login(user, pwd): if user == "alex" and pwd == "123": LOGIN_USER['is_login'] = True LOGIN_USER['current_user'] = user manager() def main(): while True: inp = input("1,后台管理;2,登录") if inp == '1': manager() elif inp == '2': username = input("请输入用户名") pwd = input("请输入密码") login(username, pwd) ------------------------------------------------
USER_INFO = {} #双层装饰器 # USER_INFO['is_login'] = True # USER_INFO['user_type'] = 2 def check_login(func): #登录验证 def inner(*args, **kwargs): if USER_INFO.get('is_login', None): ret = func(*args, **kwargs) return ret else: print('请登录') return inner def check_admin(func): #权限验证 def inner(): if USER_INFO.get('user_type', None) == 2: ret = func(1121121) return ret else: print('无权限查看') return inner @check_admin def index(a): """ 管理员的功能 :return: """ print('Index') index()