您的位置:首页 > 编程语言 > Python开发

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

  • 返回字符串个数
  • 括号内容为可迭代的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: