Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+3 votes
3 views
in Python by (3.9k points)
edited by

There are two codes, what are the difference between them:

  • Using type

import types

if type(q) is types.DictType:
    do_something()
if type(w) in types.StringTypes:
    do_something_else()

  • Using isinstance()

if isinstance(q, dict):
    do_something()
if isinstance(w, str) or isinstance(w, unicode):
    do_something_else()

2 Answers

0 votes
by (46k points)
edited by

You can use isinstance() :

if isinstance(w, (str, unicode)):
    do_something_else()

alternatively, you can use basestring abstract class:

if isinstance(w, basestring):
    do_something_else()

Hope This Helps, Happy Learning.

0 votes
by (106k points)

Here's an example where isinstance achieves something that type cannot:

class Vehicle:

    pass

class Truck(Vehicle):

    pass

in this case, a truck object is a Vehicle, but you'll get this:

isinstance(Vehicle(), Vehicle)  

type(Vehicle()) == Vehicle     

isinstance(Truck(), Vehicle)   

type(Truck()) == Vehicle      

In other words, isinstance is true for subclasses, too.

You can use the following video tutorials to clear all your doubts:-

Related questions

0 votes
1 answer
+1 vote
2 answers
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...