2012/02/28

How to get the type of an object in Python

Sometimes we need to know the type of an object in Python. For instance, when you get an object from a method and you just don't know anymore if its a list, a dict, or other, how can you know the type of the object? To solve this, you can use either the type(object) or object.__class__ commands, like it is demonstrated bellow.
d1={1:'airplane', 2:'car'}
d2= ['airplane', 'car']
print type(d1)
print d1.__class__
print type(d2)
print d2.__class__
Results in:

<type 'dict'>
<type 'dict'>
<type 'list'>
<type 'list'>

No comments:

Post a Comment