特色:app
實例函數
>>> city = ['wuhan','shenzhen','chongqing','huanggang'] >>> city <list_iterator object at 0x101402630> >>> city .__next__() #方法一:使用next方法來使用迭代器 'wuhan' >>> city .__next__() 'shenzhen' >>> city .__next__() 'chongqing' >>> city .__next__() 'huanggang' >>> city .__next__() # 若是容器中沒有更多元素了,則拋出StopIteration異常 Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration # 方法二:使用for循環來使用迭代器 it = iter(city) for x in it: print(x)
定義:post
一個包含了yield關鍵字的函數就是一個生成器,該函數也叫生成器函數。當生成器函數被調用時,在函數體中的代碼不會被執行,而會返回一個迭代器。每次請求一個值,就會執行生成器中代碼,直到遇到一個yield表達式或return語句。yield表達式表示要生成一個值,return語句表示要中止生成器。換句話說,生成器是由兩部分組成,生成器的函數和生成器的迭代器。生成器的函數是用def語句定義的,包含yield部分;生成器的迭代器是這個函數返回的部分。兩者合起來叫作生成器。spa
實例一:code
a = [i*i for i in range(1,10)] print(a) # 結果:[1, 4, 9, 16, 25, 36, 49, 64, 81]
實例二:利用生成器自定義range對象
def drange(num): temp = -1 while True: temp = temp + 1 if temp >= num: return else: yield temp
特色:blog
實例一:一個簡單裝飾器實現計算函數運行的時間utf-8
# -*- coding:utf-8 -*- # @Author : Clint # @File : calculate_time.py import time def cal_time(func): def wrapper(*args, **kwargs): start_time = time.time() x = func(*args, **kwargs) end_time = time.time() print(func.__name__+"的time cost:", end_time-start_time) return x return wrapper @cal_time #語法糖 test=timer(test)
def test_func():
time.sleep(3)
print("fun_test...") # 結果 test_func的time cost:3.000171661376953
實例一:裝飾有參函數ci
import time def timer(func): def deco(*args,**kwargs): start_time = time.time() func(*args,**kwargs) stop_time = time.time() print(stop_time-start_time) return deco @timer def test(parameter): time.sleep(3) print("test is running") test("添加參數")