Python is a powerful programming language that provides a wide range of built-in functions to make coding easier and more efficient. One such function is "isinstance()". This function is used to check if an object is an instance of a specified class or subclass.
Syntax: The syntax for the isinstance() function is as follows:
|
isinstance(object, classinfo)
|
where:
Example 1:
|
number = 10
print(isinstance(number, int))
|
In this example, the variable "number" is assigned the value of 10, which is an integer. The isinstance() function is then used to check if "number" is an instance of the "int" class. The output of this code will be "True".
Output:
|
True
|
|
class Shape:
pass
class Rectangle(Shape):
pass
rect = Rectangle()
print(isinstance(rect, Shape))
print(isinstance(rect, Rectangle))
|
In this example, we have created two classes "Shape" and "Rectangle". "Rectangle" is a subclass of "Shape". We then create an instance of the "Rectangle" class and use the isinstance() function to check if it is an instance of "Shape" or "Rectangle". The output of this code will be "True" for "Shape" and "True" for "Rectangle".
Output:
|
True
True
|
The isinstance() function can also be used to check if an object is an instance of any class within a tuple of classes. Here is an example:
Example 3:
|
class Dog:
pass
class Cat:
pass
class Bird:
pass
animal_list = [Dog(), Cat(), Bird()]
for animal in animal_list:
if isinstance(animal, (Dog, Cat)):
print("This animal is a mammal")
elif isinstance(animal, Bird):
print("This animal is a bird")
|
In this example, we have created three classes: "Dog", "Cat", and "Bird". We then create a list of animals which includes an instance of each class. We use the isinstance() function to check if each animal is a mammal or a bird. The output of this code will be "This animal is a mammal" for "Dog" and "Cat", and "This animal is a bird" for "Bird".
Output:
|
This animal is a mammal
This animal is a mammal
This animal is a bird
|