defmy_range(n):
i =0while i < n:yield i
i +=1
my_range = my_range(3)print(dir(my_range))print('__iter__'indir(my_range))print('__next__'indir(my_range))
defmy_range(n):print('开始迭代...')
i =0while i < n:print('迭代中...')yield i
print('-'*10)
i +=1print('迭代结束')
gen_obj = my_range(3)print(next(gen_obj))print(next(gen_obj))print(next(gen_obj))
defmy_range(n):
i =0while i < n:
var =yield i
print(f'var 的值为 {var}')
i +=1
my_range = my_range(3)print(my_range.send(None))print(my_range.send('hello'))print(my_range.send('world'))
defmy_range(n):
i =0while i < n:
var =yield i
print(f'var 的值为 {var}')
i +=1
my_range = my_range(3)print(my_range.send(None))print(my_range.send('hello'))
my_range.close()print(my_range.send('world'))
0
var 的值为 hello
1
Traceback (most recent call last):
File "C:/Users/FOLLOW_MY_HEART/Desktop/Python基础/【Python基础】迭代器/test.py", line 18, in<module>
print(my_range.send('world'))
StopIteration