1.1 装饰器、生成器、迭代器、调用函数、内置函数
1.1.1 装饰器
装饰器:本质势函数,(装饰其它函数)就是为其他函数添加附加功能。
原则:1、不能修改被被装饰的函数的源代码
2、不能修改被装饰的函数的调用方式
实现装饰器的知识储备:
1、函数即“变量”
2、高阶函数
3、嵌套函数
高阶函数 + 嵌套函数 = 装饰器
下面举个列子:
【高级版】
import time #申明库 def timer(func): #定义timer函数 def deco(*args,**kwargs): #定义deco函数,(嵌套函数) start_time = time.time() #获取func函数开始的时间 func(*args,**kwargs) #执行func函数 stop_time = time.time() #获取func函数结束的时间 print('the func run time is %s'%(stop_time-start_time)) #打印func函数执行的总时间 return deco #在timer函数中返回deco地址变量 @timer #装饰器 #test = timer(test) def test(): time.sleep(3) print('in the test') test()
【终极版】
# -*- coding:utf-8 -*- #!/usr/bin/env python # Author:suchagal username = 'xuwei' password = 'suchagal' def auth(auth_type): def outer_wrapper(func): def wrapper(*args, **kwargs): if auth_type == 'local': users = input('input username:').strip() passwd = input('input passwd:').strip() if users == username and passwd == password: res = func(*args, **kwargs) print('