What is the purpose of the isinstance() function in Python OOP?
Answer:
Explanation:
The isinstance()
function in Python is used to check if an object is an instance of a specific class or a tuple of classes. It returns True
if the object is an instance of the specified class or classes, and False
otherwise. This function is useful for type-checking and ensuring that objects passed to functions or methods are of the expected type.
class Animal:
pass
class Dog(Animal):
pass
# Checking instances
dog = Dog()
print(isinstance(dog, Dog)) # Output: True
print(isinstance(dog, Animal)) # Output: True
print(isinstance(dog, list)) # Output: False
In this example, the isinstance()
function checks whether the dog
object is an instance of the Dog
class, the Animal
class (its parent), and the list
class. The results reflect the inheritance relationship and class types.
Using isinstance()
is important for writing flexible and error-resistant code, as it allows you to verify that objects are of the correct type before performing operations on them.