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.
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()