python运维开发之第四天
一、装饰器
1、器:代表函数,装饰器本质是函数,(装饰器他函数)
2、功能:为其他函数添加附加功能
3、原则:
(1)不能修改被装饰函数的源代码
(2)不能修改被装饰函数的调用方式
4、实现装饰器知识储备:
(1)函数即“变量”,定义变量就是把函数体赋值给函数名(函数引用基数内存回收)
(2)高阶函数
a、把一个函数名当作实参传给另一个函数
b、返回值中包含函数名
其中a不修改源代码,b不修改调用方式
(3)嵌套函数
在函数体内去声明一个函数(def)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Willpower-chen # @blog: http://www.cnblogs.com/willpower-chen/ # # import time ''' 装饰器本质是函数,函数即‘变量’ ''' # #例子1 # def foo(): # time.sleep(3) # print('in the foo') # bar() # # foo() # #例子2 # def bar(): # print('in the bar') # def foo(): # time.sleep(3) # print('in the foo') # bar() # foo() # # # #例子3 # def foo(): # time.sleep(3) # print('in the foo') # bar() # def bar(): # print('in the bar') # foo() # # #例子4 # def foo(): # time.sleep(3) # print('in the foo') # bar() # foo() # def bar(): # print('in the bar') import time def timer(func): def recod(*args,**kwargs): start_time = time.time() func(*args,**kwargs) stop_time = time.time() run_time = stop_time - start_time print('调用%s 耗时 %s'%(func,run_time)) return recod @timer def test1(): time.sleep(3) print('in the test1') @timer def test2(name,age,sex): time.sleep(3) print('yourname is: ',name,age,sex) test1() test2('cjk','23','man')
二、生成器(generator)
1、生成器只有在调用时,才会生成相应的数据
2、生成器只记录当前位置
3、只有一个__next__()方法
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Willpower-chen # @blog: http://www.cnblogs.com/willpower-chen/ import time def consumer(name): while True: baozi = yield print("\033[32m包子%s来了\033[0m,被%s吃了!!! "% (baozi,name)) def produce(name): c = consumer('王') c2 = consumer('张') c.__next__() c2.__next__() print('%s准备做包子'%name) for i in range(10): time.sleep(3) print('%s做了两个包子'%name) c.send("韭菜馅") c2.send("牛肉馅") produce('咪咪')
三、迭代器
1、可直接作用于for循环的对象统称为可迭代对象iterable
isinstance()判断是否可迭代对象
2、可以被next()函数调用并不断返回下一个值的对象称为迭代器interator
3、list,dict,str编程iterator使用iter()函数
四、内置方法
1、匿名函数
(lambda n:print(n))(5)等价于
calc = lambada n:print(n)
calc(5)
2、filter()过滤
res = filter(lambda n:n>5,range(10))
for i in res:print(i)
五、json&pickle
1、json序列化与反序列化
(1)序列化 json.dumps()
(2)反序列化json.loads()
json只能处理简单的序列化,主要是不同语言之间的转换
2、pickle序列化与反序列化
只能在python中进行转化,支持更复杂的序列化

浙公网安备 33010602011771号