Check if the input object is instance of input classinfo.

object : Object to be checked for instance against classinfo
classinfo : object to be checked against this classinfo. Can be a tuple of more than one class

isinstance returns True if object is instance of given classinfo, False otherwise.

built in types

We have built in types in Python. We can check the object against built in types like string, integer, float, list ,tuple, set , dictionary etc.

print(isinstance(my_number,int))  # True
print(isinstance(my_str,str))     # True
print(isinstance(my_list,list))   # True
print(isinstance(my_tuple,tuple)) # True
print(isinstance(my_dict,dict))   # True
print(isinstance(my_set,set))     # True

Using tuple

We can check against more than one classinfo by using a tuple
print(isinstance(my_str,int))        # False 
print(isinstance(my_str,(int,str)))  # True 
In last line we used a tuple of ( int,str). As our string object my_str is an instance of string ( str ) class so it returns True. However in previous line we checked against integer ( int ) so we got False as output.

Using user defined class

animals() is or base or parent class. wild() is out derived or child class.
class animals():
    home='Jungle' #class attribute
#instance attributes
    def __init__(self,name,height): name
class wild(animals):
class birds(wild):
tiger=animals('Alex',4) # object of animal class created

print(isinstance(tiger,animals))  # True
print(isinstance(tiger,wild)) # False 
print(isinstance(tiger,birds)) # False

lion=wild('Tom',3)      # object of wild class created
print(isinstance(lion,animals))  # True
print(isinstance(lion,wild)) # True 
print(isinstance(lion,birds)) # False
An object of child class is also instance of parent class.

tiger is an object of animals() class so isinstance() returns False when we checked against child class wild().

In case of object lion ( an object of wild() ) the line print(isinstance(lion,animals)) returns True as wild() is child class of base class animals()

All Built in Functions in Python locals() dir() classmethod issubclass
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer