老男孩14期自動化運維day4隨筆和作業(ATM)
阿新 • • 發佈:2018-12-19
(1)裝飾器:相當於對一個函式進行功能的新增,裝飾器是由高階函式和巢狀函式的結合 使用裝飾器裝飾函式時,不能修改原函式的呼叫方式。比如登入認證時會用到裝飾器 裝飾器能夠帶引數,一下是一個高階裝飾器列子
#!/usr/bin/env python
# coding:utf-8
# Author:Yang
# 裝飾器高階版
import time
user="yang"
pwd="123"
def auth(auth_type):
print("auth func:",auth_type)
def outer_wrapper(func):
def wrapper(*args, **kwargs):
print("auth func wrapper:",*args, **kwargs)
if auth_type =="local":
username = input("username:").strip()
password = input("pwd:").strip()
if user == username and pwd == password:
print("\033[32;1m user has passed authentication\033[0m" )
res = func(*args, **kwargs) # from home
print('---')
return res
else:
exit("\033[32;1m error\033[0m")
elif auth_type=="ldap":
print("ladap")
return wrapper
return outer_wrapper
def index():
print("welcome to index page")
@auth(auth_type="local") # 本地認證 這句話相當於
def home(): # 需要登入
print("welcome to home page")
return "from home"
@auth(auth_type="ldap") # 遠端認證
def bbs(): # 需要登入
print("welcome to bbs page")
index()
print(home()) # 呼叫的wrapper
bbs()
(2)生成器 只要帶有yield關鍵字的就是生成器,且已經不是函數了
#!/usr/bin/env python
# coding:utf-8
# Author:Yang
def fib(max): # 只要有yield存在 就是生成器 且不是函數了
n,a,b=0,0,1
while n <max:
# print(b)
yield b # 儲存函式的中斷狀態
a,b=b,a+b
# a,b=b,a+b相當於 t=(b,a+b) t是一個元組
# a=t[0]
# b=t[1]
n=n+1
return 'done'
f=fib(10)
# #print('---------ddddd')
# print(f.__next__())
# print("----")
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
print('start loop')
# #for i in f:
# print(i)
(3)協程的使用。(單執行緒並行)
#!/usr/bin/env python
# coding:utf-8
# Author:Yang
import time
# 生產者消費者模型 單執行緒並行(協程)
def consumer(name):# 消費者
print("%s 準備吃包子了"%name)
while True:
baozi=yield
print("包子[%s]來了,被[%s]吃了"%(baozi,name))
c=consumer("yhr")
c.__next__()
# b1="韭菜餡"
# c.send(b1) # 呼叫yield 傳值 (喚醒傳值)
# c.__next__() # 呼叫yield 不傳值 (只喚醒)
def producer(name): #生產者
c = consumer('A')
c2 = consumer('B')
c.__next__()
c2.__next__()
print("老子開始做包子了")
for i in range(10):
time.sleep(1)
print("做了一個包子,分兩半")
c.send(i)
c2.send(i)
producer("yang")
(4)迭代器 –可迭代物件iterable,凡是可作用於for 迴圈的都是iterable物件,list,dict,tuple,str是可迭代物件 –迭代器iterator,凡是可作用於next()函式的物件都是iterator物件,表示一個惰性計算的序列, 使用b=iter(a)講a轉為iterator物件 注:在python 2.x版本中,range(10)得到的結果是列表,是一個iterable物件。在python 3.x版本中 range(10)得到的是一個iterator物件
#!/usr/bin/env python
# coding:utf-8
# Author:Yang
from collections import Iterable
a=[1,2,3]
print(dir(a))
print(isinstance(a,Iterable))
# 生成器都是iterator物件,list,dict,tuple,str 是Iterbale,卻不是iterator
# 凡是可作用與for迴圈的物件都是iterable物件
# 凡是可作用與next()函式的兌現個都是iterator物件,表示一個惰性計算的序列
# b=iter(a) 將a轉為iterator物件
(5)序列化與反序列化 可在不同的語言環境,作業系統環境上進行資料的傳輸。使用Pickle作為序列化格式的時候,可以將物件傳入,但是隻能在python語言中執行,且pickle實際上傳輸的是函式的記憶體地址 (json 與pickle) 序列化:
#!/usr/bin/env python
# coding:utf-8
# Author:Yang
import json
import pickle
def sayhi():
name='yhr'
print("hello",name)
info ={
'name':'yang',
'age':22
}
f = open("test.txt","w") # 寫json 傳簡單資料
f.write(json.dumps(info))
# f=open('test2.txt','wb') # 寫pickle 能序列化函式物件 傳輸記憶體地址
# f.write(pickle.dumps(info)) # f.write(pickle.dump(info,f)
f.close()
反序列化
#!/usr/bin/env python
# coding:utf-8
# Author:Yang
# 讀json
import json
f=open('test.txt','r')
data=json.loads(f.read())
print(data['age'])
f.close()
# print(eval(data)['age'])
# # 讀pickle
# import pickle
#
# def sayhi():
# name='yhr'
# print("hello",name)
# print("hello2")
# f=open('test2.txt','rb')
# data=pickle.loads(f.read())
# print(data)
# print(data['func']())
f.close
(6)python 3.x內建函式及用法概覽
#!/usr/bin/env python
# coding:utf-8
# Author:Yang
# 內建函式
print(all([0,-1,3])) # 判斷iterable元素 都為真則返回True 非0為真 有假則假
print(any([0,-1,3])) # 有真則真
print(ascii([1,2,"楊"])) #把記憶體的資料物件變成可列印的字串物件
print(bin(255)) # 數字十進位制轉二進位制 b 代表二進位制開頭
print(bool(0),bool(1),bool(-1)) # 判斷布林值 列表為空 字典為空 是假
a=bytes("abcde",encoding="utf-8")
b=bytearray("abcde",encoding="utf-8") #列印a的ascii形式
print(b[1])
def a():
pass
print(callable(a)) # 判斷是否可呼叫
print(chr(98)) # 把數字對應ascii
print(ord('d')) # 把ascii轉對應數字
code="for i in range(10):print(i)"
#print(compile(code,'','exec'))
#c=compile(code,'','exec') # 把字串編譯成可執行檔案
exec(code) # exec可直接執行。。。(多行)
list=[]
print(dir(list)) # 可以查方法
print(divmod(5,3)) # 得商,餘數
l=[1,2,3]
for i in enumerate(l): # 將iterable可迭代物件組成一個索引序列
print(i)
a="2*5"
d="[1,2,3]"
print(eval(a)) # 用來執行字串表示式,並返回表示式的值
print(eval(d)) # 將字串物件轉換為有效的表示式,講d轉換為list
res = filter(lambda n:n>5,range(10)) # 使用了匿名函式做條件,filter作為過濾器,在3.0 filter生成的是迭代器物件,要用for來迭代
for i in res:
print(i)
import functools
res1=functools.reduce(lambda x,y:x+y,range(10))
print(res1)
f="{} {}".format("hello","world") # 格式化字串/數字
print(f)
a=frozenset([1,3,444,55,231,3]) # 變成不可變集合
print(globals()) # 返回當前程式所有全域性變數的字典
print(hash('yang')) # 生成雜湊演算法對應雜湊值 (找字串的時候 就是雜湊值的二分查詢)
print(hex(10)) # 轉為16進位制 0x
def test():
local_var='a'
print(locals()) # 列印當前區域性變數
test()
print(oct(10)) # 轉八進位制 0o
print(oct(8))
print(round(1.3323))
print(round(1.32,2)) #保留兩位
a={6:2,-3:1,3:4}
print(sorted(a.items())) # 把key排序變成列表
print(sorted(a.items(),key=lambda x:x[1])) # 把value排序變成列表
a=[1,2,3,4]
b=['a','b','c','d']
for i in zip(a,b): # 拉鍊 組合
print(i)
__import__('decorator') # 之後會用