0

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

I want 'complex' to be printed, but nothing happend, why? How to do this right?

>>> c = (5+3j)
>>> type(c)
<type 'complex'>
>>> if type(c) == 'complex': print 'complex'
... 
>>> 
Community
  • 1
  • 1
Cadilac
  • 1,090
  • 11
  • 17

3 Answers3

5

You can use isinstance:

if isinstance(c, complex):

From the documentation:

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
2

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

Abhijit
  • 62,056
  • 18
  • 131
  • 204
2
>>> c = 5+3j
>>> c
(5+3j)
>>> type(c)
<type 'complex'>
>>> complex
<type 'complex'>
>>> type(c) == complex
True
>>> isinstance(c, complex)
True
>>>

type(c) == complex would mean "this is definitely an instance of complex, not some subclass". isinstance(c, complex) would include subclasses.

cHao
  • 84,970
  • 20
  • 145
  • 172