python学习日志(十三)"装饰器,偏函数,collections模块"
2018-12-25 22:28
106 查看
装饰器
- 有新的需求:对函数功能进行扩展,每次打印函数前打印系统时间
- 而实现这个功能又不能改动现有代码
- 定义:在不改动函数代码的基础上,无限制拓展函数功能的一种机制,本质上讲,装饰器是一个返回函数的高阶函数
- 使用:使用@语法,即每次要拓展到函数定义前使用@+函数名
#案例 import time def printTime(f): def wrapper(*args.**kwargs): print("Time:",time.ctime()) return wrapper #上面定义了装饰器,使用的时候需用到@ @printTime def hello(): print("hello word")
- 好处:一旦定义,可以装饰任意函数
- 一旦被装饰,则把装饰器的功能直接添加到定义函数的功能上
#手动执行装饰器 import time def printTime(f): def wrapper(*args.**kwargs): print("Time:",time.ctime()) return wrapper def hello3(): print("我是手动执行的") hello3 = printTime(hello3) hello3()
偏函数
- 把字符串转化成十进制数字
int('12345')
- 求八进制的字符串12345,表示成十进制的数字是多少
int("12345",base=8)
#新建一个函数,此函数是默认输入的字符串是16进制数字 #把字符串返回十进制数字 def int16(x,base=16) return int (x,base) int("12345")
偏函数
- 参数固定的函数,相当于有一个特定参数的函数体
- funtools.partial的作用是把一个函数某些参数固定,返回一个新函数
#案例 import funtools #实现上述函数功能 int16 = funtools.partial(int,base=16) int16("123456")
zip
- 把两个可迭代内容生成一个可迭代的tuple类型组成的内容
#案例 l1 = [1,2,3,4,5] l2 = [11,22,33,44,55] z = zip(l1,l2) #可迭代便可用for循环
enumerate
- 跟zip功能比较像
- 对可迭代对象里每一个对象,配上一个索引,然后索引和内容构成tuple类型
- 默认从0开始,可由start配置
collections模块
- namedtuple
- 是tuple类型
- 是一个可命名的tuple
#案例 import collections point = collections.namedtuple("point",["x","y"]) p = point(11,22) #定义一个圆 circle = collection.namedtuple("circle",["x","y","r"]) c = circle(100,150,50)
- deque
- 比较方便地解决了频繁删除插入带来的效率问题
#案例 from collections import deque q = deque(["a","b","c"]) print(q) q.append("d") print(q) q.appendleft("x") print(q)
- defaultdict
- 当直接读取dict不存在属性时,直接返回默认值
- counter
- 返回字符串个数
- 括号内容为可迭代的
相关文章推荐
- Python学习日志之二-----装饰器
- Python基础学习:函数装饰器
- python学习笔记3.4-函数装饰器
- Python 函数修饰符(装饰器)的学习
- python的函数装饰器学习笔记
- Python学习(九)——匿名函数、装饰器、偏函数
- python学习系列之python装饰器基础(2)---装饰含返回值的函数
- python学习笔记之基础操作(七)函数闭包和装饰器
- python 函数装饰器学习
- python学习笔记12(装饰器、偏函数、变量作用域)
- python学习笔记,返回函数,匿名函数,装饰器
- Python学习 Day 5 高阶函数 map/reduce filter sorter 返回函数 匿名函数 装饰器 偏函数
- 9、Python学习笔记--函数递归、装饰器
- 我的Python学习之路十三:函数(二)
- python学习笔记之函数总结--高阶函数以及装饰器
- Python学习3--返回函数 、匿名函数、装饰器、偏函数
- 【Python】学习笔记十三:函数的参数对应
- Python学习日志(三)—— 函数
- 十三、python学习之python高级三(闭包和装饰器)
- Python学习日志 - 8.函数(习题解答)