Skip to main content
 首页 » 编程设计

python之Python 中 set() 的类型是什么

2025年05月04日11zhujiabin

a = ['a', 'b', 'c', 'd'] 
b = set(a) 
print isinstance(a, types.ListType) 
print isinstance(b, types.ListType) 

结果表明b不是types.ListType。但是,Python 中没有“SetType”。那么什么是 'XXXType' 类型才能使 isinstance(b, types.XXXType) 为 True?

请您参考如下方法:

使用isinstance(b, set)。

types 对内置类型的引用只是为了方便*,否则已弃用(它们已从 Python 3.x version of the types module 中删除)。因此 set 从未被添加。

例如,types.ListType只是list的别名:

>>> import types 
>>> types.ListType is list 
True 
>>> isinstance([1, 2, 3], list) 
True 

如果您必须在types 模块中有一个SetType 引用,只需自己添加别名:

types.SetType = set 

如果您正在寻找基本容器类型的抽象基类,请使用 collections module ABCs ;这些表明一个类型支持什么方法,并且针对这些类型进行检查可以让您检测到支持特定操作的更广泛的类型集(而不是仅仅是 list 的实例和设置类型:

>>> from collections import Set, MutableSequence 
>>> isinstance([1, 2, 3], MutableSequence) 
True 
>>> isinstance({1, 2, 3}, Set) 
True 

* 历史教训:曾几何时,int 和 list 等内置类型是不是真正的类,内置名称 int() 和 list() 只是转换为内置类型的函数。这意味着名称与 types.IntType 和 types.ListType 根本不是同一个对象,您必须使用类型 模块,以便能够在列表对象上使用 isinstance()。那个时代已经过去很久很久了,types 模块的角色已经改变。