What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Python isinstance() Function (with Examples)

  • Sep 21, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Abrar Ahmed
Python isinstance() Function (with Examples)

The isinstance() is a fundamental Python function that is frequently used in numerous programming paradigms such as object-oriented programming, functional programming, and others. Let's learn more about it.

Python isinstance() Function

The isinstance() function in Python determines if an object belongs to a single class or a tuple of classes. It aids in determining an object's type and permits conditional actions based on that kind.

If the object is an instance or subclass of the provided class or classes, it returns True; otherwise, it returns False. This function is useful for testing polymorphic behavior and doing different actions depending on the type of object. 

An example code to check if an object is an instance of any class in a tuple:

class MyClass:
    pass
class AnotherClass:
    pass
obj = MyClass()
print(isinstance(obj, (MyClass, AnotherClass)))  # Output: True
print(isinstance(obj, (str, int)))               # Output: False

 

We have two classes in the above example: MyClass and AnotherClass. We make an obj instance of MyClass. Isinstance(obj, (MyClass, AnotherClass)) determines whether obj is an instance of MyClass or AnotherClass. Because obj is a MyClass instance, the output is True. However, when we check to see if obj is a str or int instance, which it isn't, the output is False.

An example that demonstrates the usage of isinstance() in Python:

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!")
animals = [Dog("Buddy"), Cat("Whiskers"), Dog("Max"), Cat("Oliver")]
for animal in animals:
    if isinstance(animal, Dog):
        animal.bark()
    elif isinstance(animal, Cat):
        animal.meow()

 

In this case, we have a base class called Animal and two derived classes called Dog and Cat. We establish an animal list that contains instances of these classes. We iterate through the list, checking the type of each animal using isinstance(). If the animal is a Dog instance, we use the bark() method from the Dog class. If the animal is a Cat instance, we use the Cat class's meow() method.

Is Isinstance () a built-in function in Python?

Yes, isntance() is a built-in function in Python. It is part of the Python standard library and does not necessitate the inclusion of any additional import lines in your code. The function isinstance() is available in all Python contexts and versions.

What are its parameters?

Python's isinstance() method takes two parameters: object and classinfo.

  1. Object: This argument describes the object whose type you want to determine. It can be any legal Python object, such as variables, class instances, or literals.
  2. classinfo: This argument defines the class or classes to which the type of object is compared. It can manifest itself in the following ways:

Difference between Isinstance() and type()

In Python, the isinstance() and type() functions are used to determine the type of an object. Their behavior and application cases, however, differ slightly.

The isinstance function determines if an object is an instance of a particular class or a subclass of that class. It takes inheritance into account and can match against several classes by passing a tuple of classes as classinfo. On the other hand, type() function returns an object's actual class or type. It ignores inheritance and returns the object's particular class.

Also, isinstance() takes into consideration inheritance, but type() doesn't.

Conclusion

To conclude, Python's isinstance() method is a strong tool for type verification and conditional reasoning based on object types. It is especially handy when dealing with polymorphic behaviour, since it allows code to handle objects of multiple classes in a consistent manner.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Abrar Ahmed
An ambivert individual with a thirst for knowledge and passion to achieve. Striving to connect Artificial Intelligence in all aspects of life. I am also an avid coder and partake in coding challenges all the time on Leetcode and CodeChef.