学习笔记(五)装饰器、迭代器、匿名函数
来源:互联网 发布:亚马逊德国站情况知乎 编辑:程序博客网 时间:2024/06/04 23:59
1.装饰器=高阶函数+嵌套函数
定义:本质是函数(装饰其他函数),是其他函数的附加功能
原则:
1.不能修改被装饰的函数的源代码
2.不能修改被装饰的函数的调用方式
储备:
1.函数即变量
2.高阶函数
a.把一个函数名当做实参传递给另外一个函数(原则1)
b.返回值中包含函数名(原则2)
3.嵌套函数
#以下符合原则1,不符合原则2.高阶函数的adef 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 funcprint(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 decodef test1(): time.sleep(3) print('in the test1')test1=timer(test1)#可改成@CreatorName,=test1=timer(test1),并且放在被修饰函数的前面test1()import timedef 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@timmerdef 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.pyimport os,sysBaseDir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.append(BaseDir)from project import main
阅读全文
0 0
- 学习笔记(五)装饰器、迭代器、匿名函数
- python 学习笔记---匿名函数 装饰器 偏函数
- python学习笔记,返回函数,匿名函数,装饰器
- python学习笔记 匿名函数和装饰器
- Scala 学习笔记(五)------定义匿名函数
- 11月27日学习笔记_匿名函数/装饰器
- python_装饰器/匿名函数
- python函数式编程之返回函数、匿名函数、装饰器、偏函数学习
- 装饰器学习笔记3:简单的函数装饰器
- Python学习3--返回函数 、匿名函数、装饰器、偏函数
- Python学习(九)——匿名函数、装饰器、偏函数
- Python学习笔记-匿名函数
- python函数式编程:匿名函数,装饰器,偏函数
- 函数作为返回值/匿名函数/装饰器
- 【Python学习笔记】函数式编程:装饰器
- 装饰器学习笔记1:函数的作用域
- 《Fluent Python》学习笔记 chpter7函数装饰器
- python基础—(高阶,匿名,偏)函数 | 装饰器
- showCase(new String('A'));
- 等高布局
- Mac系统中Python3的安装与切换
- C++输入输出格式问题
- Android之Linerlayout、RelativeLayout、FrameLayout性能比较
- 学习笔记(五)装饰器、迭代器、匿名函数
- 操作系统之分段
- JavaScript数字
- 单身狗脱单算法 脱单了算你赢
- 数据库——SQL中like与通配符的使用
- 异常
- 9月21日
- View的事件分发机制
- Android进阶三:自定义View