装饰器
定义:本质是函数(装饰器他函数)为了其他函数添加附加功能
原则:1、不能修改被装饰的函数的源代码
2、不能修改被装饰的函数的调用方式
实现装饰器需要掌握的点:
1、函数即“变量”
2、高阶函数
3、嵌套函数
装饰器=高阶函数+嵌套函数
1 #!usr/bin/python 2 #_*_coding:utf-8*_ 3 #author:moll 4 import time 5 #第一个版本: 6 username="moll" 7 password="123" 8 def decorator(authr_type): 9 print("type is %s"%authr_type) 10 def outer_decorator(func): 11 def wapper(*args,**kwargs): 12 print(*args,**kwargs) 13 use = input("input the user:").strip() 14 pwd = input("input the pwd:").strip() 15 if authr_type=="local01": 16 if use==username and pwd==password: 17 print("you are right") 18 res =func(*args,**kwargs) 19 print("返回结果为-----------------------") 20 return res 21 else: 22 exit("valid datas") 23 elif authr_type=="local02": 24 print("搞毛线,dab") 25 else: 26 print("一切都结束了") 27 return wapper 28 return outer_decorator 29 30 @decorator(authr_type="local01") 31 def index(): 32 print("welcome to inxdex") 33 return "today is monday" 34 @decorator(authr_type="local02") 35 def home(): 36 print("welcome to home") 37 return "today is sunday" 38 @decorator(authr_type="local03") 39 def bbs(): 40 print("welcome to bbs") 41 print(index()) 42 home() 43 bbs() 44 45 #第二个版本: 46 username="moll" 47 password="1" 48 def author(author_type): 49 def outer_wapper(func): 50 print("the author_type is %s"%author_type) 51 def timer(*args,**kwargs): 52 53 user=input("input the username:") 54 pwd=input("input the password") 55 if author_type == "local01": 56 if user=="moll" and pwd=="1": 57 res=func(*args,**kwargs) 58 print("you are right") 59 return res 60 else: 61 exit("valid data") 62 elif author_type=="local02": 63 print("没有") 64 else: 65 print("大大地没有") 66 return timer 67 return outer_wapper 68 #装饰器传递装饰器的类型,根据不同的类型进行判断 69 @author(author_type="local01") 70 def index(): 71 print("welcome to index") 72 return "index" 73 @author(author_type="local02") 74 def home(): 75 print("welcome to home") 76 77 @author(author_type="local03") 78 def bbs(): 79 print("welocom to bbs") 80 81 print(index()) 82 home() 83 bbs()

浙公网安备 33010602011771号