i代表迭代器,g代表生成器
import pickle, time
def gen():
j = 0
while j < 7:
j += 1
yield j
i = iter([1, 2, 3])
g = gen()
print('i', type(i))
print('g', type(g))
print('i.__dir__()', i.__dir__())
print('g.__dir__()', g.__dir__())
print('next(i)', next(i))
print('next(g)', next(g))
print('i序列化', pickle.dumps(i))
time.sleep(1)
print('g序列化', pickle.dumps(g))
代码输出如下
/Users/xxx/PycharmProjects/Test7788/venv/bin/python /Users/xxx/PycharmProjects/Test7788/test5.py
i <class 'list_iterator'>
g <class 'generator'>
i.__dir__() ['__getattribute__', '__iter__', '__next__', '__length_hint__', '__reduce__', '__setstate__', '__doc__', '__repr__', '__hash__', '__str__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__init__', '__new__', '__reduce_ex__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
g.__dir__() ['__repr__', '__getattribute__', '__iter__', '__next__', '__del__', 'send', 'throw', 'close', 'gi_frame', 'gi_running', 'gi_code', '__name__', '__qualname__', 'gi_yieldfrom', '__doc__', '__hash__', '__str__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__init__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
next(i) 1
next(g) 1
i序列化 b'\x80\x03cbuiltins\niter\nq\x00]q\x01(K\x01K\x02K\x03e\x85q\x02Rq\x03K\x01b.'
Traceback (most recent call last):
File "/Users/xxx/PycharmProjects/Test7788/test5.py", line 60, in <module>
print('g序列化', pickle.dumps(g))
TypeError: can't pickle generator objects
Process finished with exit code 1
可以看到,i和g是不同类的实例,拥有的属性也不同,虽然都可以使用next方法取值,但是i可以序列化,g不可以序列化,说明g的值是运行时动态生成,而i值是固定生成