可迭代對象的生成器yield,很多人對其都模棱兩可。
在一個函數中,如果使用了yield,即使包含return,它也是可迭代的。而yield其實就是return。
yield和迭代器一樣包含__next__()方法,通過這個方法就可以使用它。
在方法運行到yield時,可以對當前函數的運行狀態做出一個記錄,將yield右邊的值作爲返回值,其返回給函數並交回控制權,當再次調用__next__()時,會直接從yield下面的語句運行,這一點類似於嵌入式中的中斷系統,不同的是中斷系統是CPU自動控制的,而yield語句是可以人爲手動控制,也可以自動控制。
所以,生成器yiled就相當於,一個方法可以被多次執行,並且記錄,產生一個可迭代的內容,我們可以通過遍歷這個可迭代的內容來使用它,也可以通過next()方法使用。
yield將其下面的程序暫時封存起來,next調用時再執行,還有一個好處是可以避免循環卡死,調試使用時可控性高。
下面是一些簡單測試的代碼:
import random
"""
This class can make a range iterable container
arguments : number of elements ,start number, stop number
"""
class Rand_Iter(object):
def __init__(self, num, start, stop):
self.num = num
self.start = start
self.stop = stop
def get_iter(self):
while self.num > 0:
rand = random.randint(self.start, self.stop)
yield rand
self.num -= 1
"""
this class can sort
a iterable container and will return a sorted list
"""
class IterList_Sort(object):
def __init__(self, iter=None):
self.iter = iter
self.list = []
if iter is not None:
for val in self.iter:
self.list.append(val)
# alter iterable container to a list
def add_elements(self, add_list):
for elem in add_list:
self.list.append(elem)
# sort algorithm with a order argument
def sort_fuc(self, order):
list = self.list
bool = lambda x, y: True if x > y else False
for i in range(0, len(list)):
for j in range(i, len(list)):
if order == 'ascend':
if bool(list[i], list[j]):
list[i], list[j] = list[j], list[i]
elif order == 'descend':
if not bool(list[i], list[j]):
list[i], list[j] = list[j], list[i]
return list
# get a sorted list(ascend)
def ascend_sort(self):
return self.sort_fuc('ascend')
# get a sorted list(descend)
def descend_sort(self):
return self.sort_fuc('descend')
# get number of the elem in the iterable containers
def get_length(self):
print("the iterable container length is ", len(self.list))
return len(self.list)
def view_list(self):
print("The Original List:")
print(self.list)
print("The Ascend List:")
print(self.ascend_sort())
print("The Descend List:")
print(self.descend_sort())
if __name__ == "__main__":
list = IterList_Sort()
list.view_list()
list.add_elements([5,2,1,3,4])
list.view_list()
list.get_length()
list.add_elements(Rand_Iter(10, 1, 100).get_iter())
list.view_list()
運行結果:
The Original List:
[]
The Ascend List:
[]
The Descend List:
[]
The Original List:
[5, 2, 1, 3, 4]
The Ascend List:
[1, 2, 3, 4, 5]
The Descend List:
[5, 4, 3, 2, 1]
the iterable container length is 5
The Original List:
[5, 4, 3, 2, 1, 46, 56, 98, 33, 69, 97, 56, 21, 20, 1]
The Ascend List:
[1, 1, 2, 3, 4, 5, 20, 21, 33, 46, 56, 56, 69, 97, 98]
The Descend List:
[98, 97, 69, 56, 56, 46, 33, 21, 20, 5, 4, 3, 2, 1, 1]
Process finished with exit code 0