【发布时间】:2018-08-24 09:06:31
【问题描述】:
在 Python 3 中,我需要测试我的变量是否具有“dict_items”类型,所以我尝试了类似的方法:
>>> d={'a':1,'b':2}
>>> d.items()
dict_items([('a', 1), ('b', 2)])
>>> isinstance(d.items(),dict_items)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dict_items' is not defined
但dict_items 不是已知类型。它也没有在types 模块中定义。如何测试类型为 dict_items 的对象(不消耗数据)?
【问题讨论】:
-
没有办法直接得到它,你可以使用
type({}.items())或使用abc.ItemsView,基本上就是same thing internally。typesmodule下的很多其他类型也是同样的定义方式。
标签: python python-3.x dictionary types python-collections