本章内容
1.装饰器
2.生成器
3.迭代器
4.内置函数
5.相对路径,绝对路径
6.(time)时间模块,random
7.json,pickle
8.shutil(复制,压缩,解压)
9.shelve
10.xml
11.configparser
12.hashlib
13.logging
14.re(正则表达式)
装饰器
装饰器
定义 :本质是函数,(装饰其他函数)就是为其他函数添加附加功能
原则:1.不能修改被装饰的函数的源代码
2.不能修改被装饰的函数的调用方式
实现装饰器的知识储备:
1.函数即使变量
2.高阶函数
3.嵌套函数
高阶函数+嵌套函数=装饰器
高阶函数
def bar():
time.sleep(3)
print('in the bar')
def test1(func):
start_time=time.time()
func()
stop_time=time.time()
print("thn func run time is %s" %(start_time-stop_time))
test1(bar)
高阶函数+return
def bar():
time.sleep(3)
print('in the bar')
def test2(func):
print(func)
return func
bar=test2(bar)
bar()
装饰器
def timer(func):
def deco():
start_time=time.time()
func()
stop_time=time.time()
print('thn func run time is %s'%(start_time-stop_time))
return deco
@timer
def test1():
time.sleep(3)
print('in the test1')
@timer
def test2():
time.sleep(3)
print('in the test2')
test1()
test2()
@timer == test1=timer(test1)
装饰器实参形参
def timer(func):
def deco(*args,**kwargs):
start_time=time.time()
func(*args,**kwargs)
stop_time=time.time()
print("testas,testas %s" %(start_time-stop_time))
return deco
@timer
def test1(name,age):
time.sleep(1)
print("testasd",name,age)
@timer
def test2():
time.sleep(1)
print("testas")
test1('alex',55)
test2()
复杂装饰器
1 user,passwd = "alex",'abc789' 2 3 def auth(auth_type): 4 def outer_wrapper(func): 5 def wrapper(*args,**kwargs): 6 if auth_type == "local": 7 username=input("Username:").strip() 8 password=input("Password:").strip() 9 if username == user and password == passwd: 10 print("