Using the isinstance() Function in Python

python isinstance

One of the most important concepts in Object-Oriented Programming (OOP) is inheritance, which allows one class to inherit attributes and methods from another class. In Python, you can use the isinstance() function to check if an object is an instance of a particular class or a subclass of that class.

How to Use Python isinstance

The syntax for isinstance() is as follows:

isinstance(object, classinfo)

Here, object is the object you want to check, and classinfo is either a class or a tuple of classes. The function returns True if the object is an instance of the specified class or a subclass thereof, and False otherwise.

Example 1: Using isinstance with Built-in Types

x = 5
y = "hello"
z = [1, 2, 3]

print(isinstance(x, int))   # True
print(isinstance(y, str))   # True
print(isinstance(z, list))  # True

In this example, we use isinstance() to check if x is an instance of the int class, if y is an instance of the str class, and if z is an instance of the list class. In all three cases, the function returns True.

Example 2: Using isinstance with User-Defined Classes

class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def bark(self):
        print("Woof!")

class Cat(Animal):
    def meow(self):
        print("Meow!")

d = Dog("Fido")
c = Cat("Whiskers")

print(isinstance(d, Animal))  # True
print(isinstance(c, Animal))  # True
print(isinstance(d, Cat))     # False
print(isinstance(c, Dog))     # False

In this example, we define a base Animal class and two subclasses, Dog and Cat. We then create instances of each subclass and use isinstance() to check if they are instances of the Animal class. Since both Dog and Cat inherit from Animal, the function returns True in both cases. However, since d is not an instance of the Cat class and c is not an instance of the Dog class, the function returns False in both cases.

Example 3: Using isinstance with Tuples

t = (1, 2, 3)

print(isinstance(t, tuple))    # True
print(isinstance(t, list))     # False
print(isinstance(t, (list, tuple)))  # True

In this example, we create a tuple t and use isinstance() to check if it is an instance of the tuple class and the list class. Since t is not an instance of list, the function returns False. By passing a tuple of classes to classinfo, we can check if t is an instance of either list or tuple. In this case, the function returns True.

Example 4: Using isinstance with Inheritance

class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model

class ElectricCar(Car):
    def __init__(self, make, model, battery_size):
        super().__init__(make, model)
        self.battery_size = battery_size

class GasCar(Car):
    def __init__(self, make, model, mpg):
        super().__init__(make, model)
        self.mpg = mpg

e = ElectricCar("Tesla", "Model S", 100)
g = GasCar("Ford", "Mustang", 25)

print(isinstance(e, Car))     # True
print(isinstance(g, Car))     # True
print(isinstance(e, GasCar))  # False
print(isinstance(g, ElectricCar))  # False

In this example, we define a Car class and two subclasses, ElectricCar and GasCar. We then create instances of each subclass and use isinstance() to check if they are instances of the Car class. Since both ElectricCar and GasCar inherit from Car, the function returns True in both cases. However, since e is not an instance of the GasCar class and g is not an instance of the ElectricCar class, the function returns False in both cases.

Example 5: Using isinstance with Multiple Inheritance

class A:
    def method(self):
        print("A")

class B:
    def method(self):
        print("B")

class C(A, B):
    pass

class D(B, A):
    pass

c = C()
d = D()

c.method()  # "A"
d.method()  # "B"
print(isinstance(c, A))  # True
print(isinstance(c, B))  # True
print(isinstance(d, A))  # True
print(isinstance(d, B))  # True

In this example, we define two classes, A and B, each with a method() that prints a different message. We then define two subclasses, C and D, that inherit from both A and B. Finally, we create instances of each subclass and use isinstance() to check if they are instances of A and B. Since C and D inherit from both A and B, the function returns True in both cases.

type()

The type() function returns the class of an object. For example:

x = 5
print(type(x))  # <class 'int'>

issubclass()

The issubclass() function checks if a class is a subclass of another class. For example:

class Animal:
    pass

class Dog(Animal):
    pass

print(issubclass(Dog, Animal))  # True

isinstance() vs type()

While isinstance() checks if an object is an instance of a particular class or a subclass of that class, type() returns the actual class of the object. For example:

class Animal:
    pass

class Dog(Animal):
    pass

d = Dog()

print(isinstance(d, Animal))  # True
print(type(d) == Animal)      # False

Here, isinstance(d, Animal) returns True because d is an instance of the Dog class, which is a subclass of the Animal class. However, type(d) == Animal returns False because the actual class of d is Dog, not Animal.

Conclusion

The isinstance() function is a powerful tool for checking if an object is an instance of a particular class or a subclass of that class. By using isinstance() in combination with other OOP concepts like inheritance, you can write flexible, reusable code that can be adapted to a wide range of use cases.