isinstance()

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.
isinstance(ojbect,classinfo)

built in types

We have built in types in Python. We can check the object aginst built in types like string, integer, float, list ,tuple, set , dictionary etc .
my_number=34
my_str='plus2net'
my_list=['a','b','c']
my_tuple=('x','y','z')
my_dict={1:'One',2:'Two',3:'Three'}
my_set={'one','two','three'}

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
my_str='plus2net'
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):
        self.name= name
        self.height=height
class wild(animals):
    weight=2
class birds(wild):
    name='Eagle'
    
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


plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer