Python’s isinstance() Function

Learn Python @ Freshers.in

Python is a versatile programming language known for its simplicity and readability. One of its many powerful features is the isinstance() function, which allows developers to check the type of an object. In this comprehensive guide, we’ll delve into the details of isinstance(), exploring its syntax, applications, and practical examples to help you master this essential tool in Python programming.

Understanding isinstance() Function:

The isinstance() function is used to check if an object belongs to a specific class or data type. Its syntax is as follows:

isinstance(object, classinfo)
  • object: The object whose type is to be checked.
  • classinfo: A class or a tuple of classes to check against.

Example 1: Basic Usage

Let’s start with a simple example:

x = 5
print(isinstance(x, int))  # Output: True

Here, isinstance() checks if the variable x is of type int, which it is, hence the output is True.

Example 2: Checking Against Multiple Types

You can also pass a tuple of classes to check against multiple types:

y = "Hello"
print(isinstance(y, (int, str)))  # Output: True

In this case, isinstance() checks if y is either an int or a str, which it is (y is a str), so the output is True.

Example 3: Using isinstance() with Inheritance

The isinstance() function also considers inheritance:

class A:
    pass

class B(A):
    pass

obj = B()
print(isinstance(obj, A))  # Output: True

In this example, obj is an instance of class B, which is derived from class A. Thus, isinstance() returns True when checking against class A.

Example 4: Handling Polymorphism

isinstance() is useful for handling polymorphism, as it allows you to check for specific types within a hierarchy:

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

pets = [Dog(), Cat()]

for pet in pets:
    if isinstance(pet, Animal):
        print(pet.speak())

In this example, we have a list of pets consisting of instances of Dog and Cat classes. We iterate through the list and use isinstance() to ensure each element is an Animal before calling its speak() method, resulting in the appropriate sound being printed for each pet.

Author: user