关于python:如何检查对象类型?

How can i check type of object?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Python - Determine the type of an object?

我想把"复杂"打印出来,但什么都没有发生,为什么?如何正确处理?

1
2
3
4
5
6
>>> c = (5+3j)
>>> type(c)
<type 'complex'>
>>> if type(c) == 'complex': print 'complex'
...
>>>

您可以使用isinstance

1
if isinstance(c, complex):

从文档中:

Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. Also return true if classinfo is a type object (new-style class) and object is an object of that type or of a (direct, indirect or virtual) subclass thereof.


1
2
3
4
5
6
7
8
9
10
11
12
>>> c = 5+3j
>>> c
(5+3j)
>>> type(c)
<type 'complex'>
>>> complex
<type 'complex'>
>>> type(c) == complex
True
>>> isinstance(c, complex)
True
>>>

type(c) == complex的意思是"这绝对是complex的一个实例,而不是某些子类"。isinstance(c, complex)将包括子类。


试试if isinstance(c,complex): print 'complex'