Python成長之路 基礎篇4

基礎篇4

一、裝飾器

二、迭代器與生成器

三、Json與pickle數據序列化

四、內置方法

1、裝飾器

裝飾器:python

裝飾器本質上就是函數,用於裝飾其餘函數,給其它函數附加一些自己所沒有的功能json

一、裝飾器遵循的一些原則

  1)不可以改變被修飾函數的源代碼。網絡

  2)不可以改變被修飾函數的調用方式。數據結構

  3)不可以改變函數執行的結果多線程

裝飾器對於要裝飾的函數來講就是至關於透明。 app

二、裝飾器須要知道的一些知識

  1)函數即「變量」函數

  2)高階函數編碼

    a、把一個函數當作實參傳遞給另外一個函數線程

    b、返回值中包含函數名code

  3)嵌套函數

    a、在一個函數裏面聲明另一個函數叫作嵌套函數

能夠說  高階函數+嵌套函數 => 裝飾器

裝飾器的列子:

#裝飾器的一個列子
import time

def func():
    time.sleep(2)
    print("This is a test")

func()

#如今有一個需求
# 給上面的函數加一個計算時間的功能
#使用裝飾器

#--------------------------------------------------------------
#修改後的代碼
import time

def timer(func):
    def wrapper():
        start_time = time.time()
        func()
        stop_time = time.time()
        print("test function run time is %s" % (stop_time - start_time))
    return wrapper   #返回的是wrapper函數名的在內存中的位置

def func2():
    time.sleep(2)
    print("This is a test")

func2 = timer(func2)  #至關於timer(func2) = wrapper = func2
func2()

#--------------------------------------------------
#由於有Python的語法糖因此代碼能夠這樣
import time

def timer(func):
    def wrapper():
        start_time = time.time()
        func()
        stop_time = time.time()
        print("test function run time is %s" % (stop_time - start_time))
    return wrapper

@timer  #至關於func2 = timer(func2) = wrapper# 給那個函數加該功能就在這個函數上面加@(功能函數)
def func2():
    time.sleep(2)
    print("This is a test")

func2()
#----------------------------------------
#若是咱們運行的函數有參數
import time

def timer(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        func(*args, **kwargs)
        stop_time = time.time()
        print("test function run time is %s" % (stop_time - start_time))
    return wrapper

@timer  #至關於func2 = timer(func2)# 給那個函數加該功能就在這個函數上面加@(功能函數)
def func2(arg):
    time.sleep(2)
    print("This is a test")

func2('test')
#這樣無論咱們傳參的時候傳幾個參數均可以把給功能加到想要家的函數上
#上面的列子中包含了高階函數和嵌套函數

#----------------------------------------------
#上面的方法只可以在咱們被裝飾的函數沒有返回值的狀況下才行
#當被修飾的函數中有返回值時那麼上面的列子就有改變了原來函數的運行結果
#下面的列子包含返回值
import time

def timer(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        te = func(*args, **kwargs)
        stop_time = time.time()
        print("test function run time is %s" % (stop_time - start_time))
        return te
    return wrapper

@timer  #至關於func2 = timer(func2)# 給那個函數加該功能就在這個函數上面加@(功能函數)
def func2():
    time.sleep(2)
    print("This is a test")

@timer
def func3(arg):
    time.sleep(2)
    print("This is a test,test results is %s" % arg)
    return "This test is func3"

func2()
print(func3('test2'))

#下面一個關於給不一樣的函數提供不一樣的加工方式
#test登陸方式爲local登陸
#test2登陸方式爲ladp
name = "yang"
passwd = "123"
def attestation(arg):
    def out_attestation(func):
        def wrapper(*args, **kwargs):
            user_name = input("請輸入用戶名:")
            user_passwd = input("請輸入該密碼:")
            if arg == "att_local":
                if user_name == name and user_passwd == passwd:
                    print(" welcome to login successfully")
                    return func(*args, **kwargs)
                else:
                    print("The user name or password you entered is wrong")
             if arg == "att_ldap":#由於是統一認證因此把密碼和用戶信息去掉了
                # if user_name == name and user_passwd == passwd:
                #     print(" welcome to login successfully")
                #     return func(*args, **kwargs)
                # else:
                #     print("The user name or password you entered is wrong")
                #這裏把用戶名和密碼去掉了因此纔有下面代碼若是有的話下面代碼就沒了
                print(" welcome to login successfully")
                return func(*args, **kwargs)
        return wrapper
    return out_attestation

@attestation('att_local') #至關於test = wrapper。 [test=attestation('att_local')(test)]
def test():
    print("Welcome to test 1 system page")

@attestation("att_ldap")#至關於test2 = wrapper
def test2():
    print("Welcome to test 2 system page")

test()
test2()

  

2、迭代器與生成器

迭代器(iterator)

迭代器對象從集合的第一個元素開始訪問,直到全部元素被訪問完結束。

迭代器擁有兩個基本的方法:__iter()__和__next()__

在說迭代器以前咱們先了解下和區分下這幾個概念:iterable、iterator、itertion

itertion:這個是迭代,也就是一個接一個。

iterator:迭代器 ,須要知足如下條件:

  一、定義了__iter__方法,可是必須返回自身

  二、定義一個__next__方法,用來返回下一個值,且當沒有數據時,拋出StopIteration能夠保持當前狀態。

代碼以下:

li = [1, 3, 4, 6]
it = iter(li)  #有iter()方法
print(next(it))#有next()方法
print(next(it))   #可使用迭代器的方法iter.__next__()和next(iter)效果同樣
print(next(it))
print(next(it))
print(next(it))   #到這步時會出現報錯

Traceback (most recent call last):
  File "F:/python/day4/iter.py", line 7, in <module>
    print(next(it))
StopIteration
1
3
4
6
#上面是運行結果

#由於只能迭代一次因此當會報錯

  

iterable:這個是可迭代對象,知足一下任意一個條件都是iterable

  一、能夠for循環: for i in iterable

  二、能夠按index索引的對象,也就是定義getitem方法,如list,str:

  三、定義iter方法。能夠隨意返回

  四、能夠調用iter(obj)對象,而且返回一個iterator

從上面咱們能夠知道

迭代器必定是可迭代的對象。

迭代器就是可迭代的,可是可迭代的不必定是迭代器,如str、list屬於iterable可是不屬於iterator

li = [1, 3, 4, 6]
it = iter(li)
print(type(it))

print('it.__iter__',it.__iter__)#有__iter__

print('it.__next__',it.next) #有next

print('it.__iter__() is it ',it.__iter__() is it ) #返回本身

迭代器是當咱們建立列表的時候裏面元素過多的話這樣就太佔內存空間,這個時候咱們就要使用迭代器這樣就佔用的內存少點。

 

生成器

在Python中,任何使用yield的函數的都被稱爲生成器(generator)。

在python中 生成器也就是迭代器(iterator),生成器徹底遵循迭代器的要求。

生成器函數和跟普通函數不一樣的是,它把return換成yield,而且yield和return不可以共用。其中yield是一個語法糖。內部實現了迭代器協議,同時保持狀態能夠掛起。

使用yield,可讓函數生成一個序列,該函數但會的對象類型是「generator」,經過該對象連續調用next()方法返回序列值。

建立一個generator,有不少下面就是一個簡單的列子

list = [i*2 for i in range(10)]
print(list) #結果爲[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
print("list", type(list)) #結果爲list <class 'list'>

ite = (i*2 for i in range(10))
print(ite) #結果爲<generator object <genexpr> at 0x0000015EE3E4F048>
print("list", type(ite)) #結果爲list <class 'generator'>

  能夠看到咱們只是把外面的[]換成了(),而[]表示生成的是list,而()表示生成的是generator。

咱們list答應出來的是每一個元素,然而generator打印的是一個迭代器,這就是咱們爲何說生成器就是迭代器。

因此生成器咱們能夠用next(iter)方法把裏面的元素一個一個打印出來,也可使用iter.__next__()方法,通常咱們不採用前面的方法獲取元素,通常使用for循環來取元素,由於生成器屬於可迭代對象。

如下使用斐波那契數列:

def fib(max):
    a, b, n = 0, 1, 0
    while n<max:
        print(b)
        a, b =b, a+b
        n+=1

fib(8)
#結果
1
2
3
5
8
13
21

#生成器函數實現斐波那契
def fib(max):
    a, b, n = 0, 1, 0
    while n<max:
        yield b
        a, b =b, a+b
        n+=1

print(fib(8))#結果爲 <generator object fib at 0x00000235374FF048>
#使函數成爲一個生成器
def fib(max):
    a, b, n = 0, 1, 0
    while n<max:
        yield b
        a, b =b, a+b
        n+=1
f = fib(10)
while True:  #用於捕捉異常
    try:
        print(next(f), end=" ")
    except StopIteration as e:
        print('Generator return value:', e.value)
        break

#結果爲0 1 1 2 3 5 8 13 21 34 Generator return value:None

 有上面能夠知道當咱們把函數作成一個生成器函數,那麼當函數裏面有循環的時候當咱們遇到yield是就會中止運行。

也就是說咱們能夠運行函數裏面循環一次在出來運行別的函數一,。這樣能夠作一些別的事情。

下面的列子是python單線程下實現多線程運行效果

import time

def consumer(cons_name):#消費者
    print("%s過來買大餅" % cons_name)
    while True:
        dabing = yield

        print("%s的大餅作好了,被%s買走了"% (dabing,cons_name))

def product():#生產者
    cons = consumer("張三")
    cons2 = consumer("李四")
    cons.__next__()
    cons2.__next__()
    print("大餅師傅開始作大餅")
    for i in range(5):
        time.sleep(1.5)
        print("作了五個酸豆角餡的大餅")
        cons.send("酸豆角")
        cons2.send("酸豆角")

product()
#實現了單線程狀況下實現並程運算

  

 

3、Json與pickle數據序列化

把變量從內存中變成可儲存或可傳輸的過程就稱之爲序列化。在Python中稱之爲picking。

序列化以後就能夠存儲到磁盤上,或經過網絡傳輸到別的機器上。有序列化就有反序列化,把內容從序列化對象從新讀取到內存的過程稱之爲反序列化。

json

序列化

import json

dic = {
    'name':'張三',
    'age':30
}

f = open('json.txt','w')
f.write(json.dumps(dic))
f.close()

  反序列化

import json

f = open("json.txt", 'r')

data2 = json.load(f)

f.close()

pickle

序列化

import pickle

dic = {
    'name':'張三',
    'age':30
}

f = open('json.txt','wb')
f.write(pickle.dumps(dic))
f.close()

  反序列化

import pickle

f = open("json.txt", 'rb')

data2 = pickle.load(f)

f.close()

  json和pickle的區別

一、json只能處理簡單的數據結構,而pickle可以處理全部的數據類型(函數等)。

二、json用於多個語言之間的網絡傳輸,pickle多用於Python程序對象持久化或Python程序之間的網絡傳輸

 

4、內置方法

注:

abs(): 對傳入的參數,獲取其絕對值

>>> abs(-10)
10
>>> abs(10)
10

  傳入的參數只能是數值

all(): 接受一個可迭代的對象,若是該對象中的全部元素爲真,那麼就返回True,反之返回False

any(): 接受一個可迭代的對象,若是該對象中有一個元素爲真,那麼就返回True,反之返回False

ascii(): 調用對象__repr__()方法,獲取該對象的返回值

bin(): 二進制

oct(): 八進制

hex():十六進制

bool():判斷傳入的參數是True仍是False,None,0,"",[],{},()這些參數爲False

bytes(): 將字符串轉換爲字節,傳參的時候,第一個參數表明的是要轉換那個字符串,第二個爲按什麼編碼轉換爲字節

str():字節轉換爲字符串,第一個參數是要轉換的字節,第二個參數是按什麼編碼轉換成字符串

callable(): 判斷對象是否能夠被調用,能被調用的對象就是一個callable對象,

chr(): unicode的轉換,按照Unicode轉換成字符。

ord():  按照unicode轉換成數字

compile():  接收.py文件或字符串做爲傳入參數,將其編譯成python字節碼

eval(): 執行python代碼,並返回其執行結果。 e.g. eval("1+2+3")   eval("print(123)").   在接收用戶輸入時應避免使用eval,由於別有用心的用戶可能借此注入惡意代碼

exec(): 執行python代碼(能夠是編譯過的,也能夠是未編譯的),沒有返回結果(返回None) e.g. exec(compile("print(123)","<string>","exec"))   exec("print(123)")

dir(): 接收對象做爲參數,返回該對象的全部屬性和方法

help(): 接收對象做爲參數,更詳細地返回該對象的全部屬性和方法

divmod(100,10) : 返回一個元組(10,0),第一個元素的100/10的商,第二個元素的100/10的餘數 

enumerate(): 接收序列化類型的數據,返回一個迭代器(對象). e.g. for i,item in enumerate(['one','two','three']): print(i,item)  打印1 'one' 換行2 'two'換行 3 'three'

isinstance(object, class): 判斷對象是不是某個類的實例. e.g. isinstance([1,2,3],list)

filter(函數或者lambda表達式,可迭代的對象): 對可迭代對象中的每個元素,將其做爲實參傳入函數(或lambda表達式),若是函數返回False,將該元素丟棄,若是函數返回True,將該元素添加到filter的返回值中。注意filter返回的是一個filter對象,實際應用中每每須要用list或tuple將其轉換爲列表或元組類型. e.g. list(filter(lambda a:a>1,[1,2,3])) 返回[2,3]

map(函數或lambda表達式,可迭代的對象): 對可迭代的每個元素,將其做爲實參傳入函數,將每一次調用函數返回的結果都添加到map的返回值中。e.g. tuple(map(lambda a:a+1,(1,2,3))) 返回(2,3,4)

format(): 字符串格式化

frozenset() : 轉換爲不可變的集合

globals() : 返回一個字典,包括全部的全局變量與它的值所組成的鍵值對

locals() :  返回一個字典,包括全部的局部變量與它的值所組成的鍵值對

hash(): 對傳入參數取哈希值並返回

id():返回內存地址,可用於查看兩個變量是否指向相同一塊內存地址

input('please input:') : 提示用戶輸入,返回用戶輸入的內容(不論輸入什麼,都轉換成字符串類型)

issubclass(subclass,class) :查看這個類是不是另外一個類的派生類,若是是返回True,不然返回False

len('string') :返回字符串長度,在python3中以字符爲單位,在python2中以字節爲單位

max():接收序列化類型數據,返回其中值最大的元素

min(): ..... 返回其中值最小的元素

memoryview():  查看內存地址

next() 

iter()  

object() 

pow(x,y): 求次方,返回x**y的結果

pow(x,y,z): 返回 x**y%z 的結果

property(): 獲取對象的全部屬性

range(): 獲取隨機數或隨機字符 eg. range(10) 從0到10的隨機數

repr(): 執行傳入對象中的_repr_方法

reversed():對序列化類型數據反向排序,返回一個新的對象。注意與對象的reverse方法區別,後者是就地改變對象

sorted(): 對序列化類型數據正向排序,返回一個新的對象。注意與對象的sort方法區別,後者是就地改變對象

slice():對序列化類型數據切片,返回一個新的對象。eg. slice(起始下標,終止下標,步長),步長默認爲1

round() : 返回四捨五入後的結果

int() :轉換爲整型

list():轉換爲列表類型

set(): 轉換爲集合類型

str():轉換爲字符串類型

tuple() : 轉換爲元組類型

type(): 返回對象類型

staticmethod() : 返回靜態方法

super(): 返回基類

vars():返回當前模塊中的全部變量

zip():接收多個序列化類型的數據,對各序列化數據中的元素,按索引位置分類成一個個元組。

eg. myList = list(zip([1,2,3],['a','b','c'])) 建立myList列表[(1,'a'),(2,'b'),(3,'c')]    

mydic = dict(zip([1,2,3],['a','b','c'])) 建立mydic字典{1:'a',2:'b',3:'c'}

l1 = [1,2,3]

l2 = ['one','two','three']

list(zip(l1,l2))  返回[(1,'one'),(2,'two'),'(3,'three')] 

 

 

 

相關文章
相關標籤/搜索