【发布时间】:2019-03-28 22:25:13
【问题描述】:
Python 3 引入了在调用 range() 和 zip() 时返回的类似生成器的对象。返回的对象就像一个生成器,可以迭代一次,但不能很好地“打印”,就像enumerate() 返回参数一样。
然而,我很困惑地看到它们是不同的对象类型并且不属于 types.GeneratorType,或者至少这是 types 模块所显示的。一个可以运行的函数,例如期望生成器不会检测到它们。他们的遗产是什么?它们是否属于主要的“生成器”结构,以便它们例如可以与其他生成器一起识别吗?
import types
a = [1,2,3]
b = [4,5,6]
# create some generator-type objects
obj_zip = zip(a,b)
obj_enu = enumerate(a)
obj_r = range(10)
print(type(obj_zip))
print(type(obj_enu))
print(type(obj_r))
# checking against types.GeneratorType returns False
print(isinstance(obj_zip,types.GeneratorType))
print(isinstance(obj_enu,types.GeneratorType))
print(isinstance(obj_r,types.GeneratorType))
# checking against their own distinct object types returns True
print(isinstance(obj_zip,zip))
【问题讨论】:
-
range对象不是生成器,它们是不可变的序列类型;你可以反复迭代它们,所以它们绝对不应该是GeneratorType。
标签: python python-3.x types generator