1.装饰器=高阶函数+嵌套函数
定义:本质是函数(装饰其他函数),是其他函数的附加功能
原则:
1.不能修改被装饰的函数的源代码
2.不能修改被装饰的函数的调用方式
储备:
1.函数即变量
2.高阶函数
a.把一个函数名当做实参传递给另外一个函数(原则1)
b.返回值中包含函数名(原则2)
3.嵌套函数
#以下符合原则1,不符合原则2.高阶函数的a
def bar:
time.sleep(3)
print("this is bar")
def test1(func):#装饰器,用来装饰bar
start_time=time.time()
func()
stop_time=time.time()
print("the func run time is %s"%(time_stop-time.start))
test1(bar)
#符合原则1,符合原则2.符合高阶函数的a,b。无嵌套函数
def bar():
time.sleep(3)
print("this is bar")
def test2(func):
print(func)
return func
print(test2(bar))#有地址加上(),就能取出。
bar=test2(bar)
bar()
#符合原则1,符合原则2.符合高阶函数的a,b。有嵌套函数
def timer(func):
def deco():
start_time=time.time()
func()
stop_time=time.time()
print("the func run time is %s"%(time_stop-time_start))
print("the func run time is ",(stop_time-start_time))
return deco
def test1():
time.sleep(3)
print('in the test1')
test1=timer(test1)#可改成@CreatorName,=test1=timer(test1),并且放在被修饰函数的前面
test1()
import time
def timmer(func):
def warpper(*args,**kwargs):
start_time=time.time()
func()
stop_time=time.time()
print("the func run time is ",(stop_time-start_time))
return warpper
@timmer
def test1():
time.sleep(3)
print("in the test1")
test1()
2.匿名函数
python 使用 lambda 来创建匿名函数。
lambda只是一个表达式,函数体比def简单很多。
lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。
lambda函数拥有自己的命名空间。
虽然lambda函数看起来只能写一行,却不等同于C或C++的内联函数,后者的目的是调用小函数时不占用栈内存从而增加运行效率。
calc=lambda x:x*3
print(calc(3))
3.迭代器(Iterator)
可直接作用于for循环的对象为—可迭代对象
可被next()函数调用并不断返回下一个值的对象为—迭代器
from collection import Iterable
生成器都是迭代对象,但list、dict、str虽然都是可迭代的
却不是迭代器。把list、dict、str等变成迭代器可使用iter()函数
instance(iter([]),Iteration)
#列表生成式
print([i*2 for i in range(10)])
#生成器
print((i*2 for i in range(10)))
4.跨目录文件引用
#project.py中引用main.py
import os,sys
BaseDir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BaseDir)
from project import main