python 3.1 - DictType不属于types模块?
这是我在Windows上安装Python 3.1时发现的内容。
我可以在哪里找到其他类型,特别是DictType和StringTypes?
>>> print('\n'.join(dir(types)))
BuiltinFunctionType
BuiltinMethodType
CodeType
FrameType
FunctionType
GeneratorType
GetSetDescriptorType
LambdaType
MemberDescriptorType
MethodType
ModuleType
TracebackType
__builtins__
__doc__
__file__
__name__
__package__
>>>
2 个回答
3
在/usr/lib/python3.1这个文件夹里搜索'DictType',你会发现它只出现一次,位置在/usr/lib/python3.1/lib2to3/fixes/fix_types.py
这个文件里。在这个文件中,_TYPE_MAPPING
把DictType
映射到了dict
。
_TYPE_MAPPING = {
'BooleanType' : 'bool',
'BufferType' : 'memoryview',
'ClassType' : 'type',
'ComplexType' : 'complex',
'DictType': 'dict',
'DictionaryType' : 'dict',
'EllipsisType' : 'type(Ellipsis)',
#'FileType' : 'io.IOBase',
'FloatType': 'float',
'IntType': 'int',
'ListType': 'list',
'LongType': 'int',
'ObjectType' : 'object',
'NoneType': 'type(None)',
'NotImplementedType' : 'type(NotImplemented)',
'SliceType' : 'slice',
'StringType': 'bytes', # XXX ?
'StringTypes' : 'str', # XXX ?
'TupleType': 'tuple',
'TypeType' : 'type',
'UnicodeType': 'str',
'XRangeType' : 'range',
}
所以我觉得在Python3中,DictType
被dict
替代了。
7
根据types
模块的文档(http://docs.python.org/py3k/library/types.html),
这个模块定义了一些对象类型的名称,这些类型是标准Python解释器使用的,但不像
int
(整数)或str
(字符串)那样被直接提供给用户使用。...通常,这个模块的用途是在
isinstance()
或issubclass()
这样的检查中。
因为字典类型可以用dict
来表示,所以在这个模块中没有必要再引入这样的类型。
>>> isinstance({}, dict)
True
>>> isinstance('', str)
True
>>> isinstance({}, str)
False
>>> isinstance('', dict)
False
(关于int
和str
的例子也已经过时了。)