Checking if an Object is an Instance of a Class
How can you determine if a particular object is an instance of a specific class?
You can easily verify this in Python using the built-in isinstance()
function.
How to Use isinstance()
The isinstance()
function is used as follows:
isinstance(object, class)
This function returns a value based on the following conditions:
-
It returns
True
if the object is an instance of the specified class, or an instance of a subclass that inherits from the specified class. -
It returns
False
otherwise.
Examples of Using isinstance()
Below is an example of checking if my_dog
, an instance of the Dog
class, is an instance of various classes:
class Animal:
pass
class Fish:
pass
class Dog(Animal):
pass
my_dog = Dog()
print(isinstance(my_dog, Dog))
# True
print(isinstance(my_dog, Animal))
# True
print(isinstance(my_dog, Fish))
# False
print(isinstance(my_dog, object))
# True
print(isinstance(my_dog, int))
# False
In the code above, the my_dog
object is an instance of the Dog
class, so isinstance(my_dog, Dog)
returns True
.
Additionally, since the Dog
class inherits from the Animal
class, isinstance(my_dog, Animal)
also returns True
.
However, my_dog
is not an instance of the Fish
class, so isinstance(my_dog, Fish)
returns False
.
Lastly, since the object
class is the parent class of all classes, isinstance(my_dog, object)
returns True
.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.