装饰器 、迭代器,json,pickle,hash

第一个装饰器

 1 #装饰器的组成结构为:高阶函数+嵌套函数
 2 import time
 3 def timer(func): #timer(test1)   func = test1
 4     def deco(*args,**kwargs):
 5         first_time =time.time()
 6         func(*args,**kwargs)#run test1
 7         stop_time =time.time()
 8         print('the func run time is %s' %(stop_time-first_time))
 9     return deco
10 #如果要装饰的函数有参数的话就要通过,*args **kwargs 来进行处理
11 @timer   #等价于  test1 = timer(test1)  = deco  给要添加该功能的函数头部添加 @timer
12 def test1():
13     time.sleep(3)
14     print('in the test1')
15 @timer
16 def test2(name,age,sex):
17     print('name:%s
''age:%s
' 'sex:%s
' %(name,age,sex))
18 test1()
19 test2("zhangsan",23,"n")
View Code

 高阶装饰器案例 

 1 import time
 2 user,passwd = 'zhangsan','abc123'
 3 def auth(auth_type):
 4     print("auth func:",auth_type)
 5     def outer_warpper(func):
 6        def wrapper(*args, **kwargs):
 7            print("wrapper func args:",*args, **kwargs )
 8            if auth_type=="local":
 9                username = input("username:").strip()
10                password = input("password:").strip()
11                if user == username and passwd == password:
12                    print("