Sunday, 27 August 2017

Difference between isinstance and type in python




I was looking at some code on the web, and I saw some code I'm not used to. The one that most called my attention was:



if not isinstance(string, str):

#dosomething


What would be the difference if I did instead:



if type(string)!=str:
#dosomething

Answer



First check out all the great answers here.




type() simply returns the type of an object. Whereas, isinstance():



Returns true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.



Example:



class MyString(str):
pass


my_str = MyString()
if type(my_str) == 'str':
print 'I hope this prints'
else:
print 'cannot check subclasses'
if isinstance(my_str, str):
print 'definitely prints'


Prints:




cannot check subclasses
definitely prints

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...