In Python, the isinstance() function is an inbuilt utility that checks whether a specific object or variable is an instance of a particular class or type and returns a boolean response.
In this tutorial, we will explain and demonstrate how you can effectively apply this vital Python functionality using practical examples.
Whether you’re an entry-level coder or an advanced Python programmer, isinstance() comes in handy for conditional programming and error handling.
Step 1: Basic Use of Isinstance()
Let’s start our tutorial with a fundamental example of isinstance() in play. The function typically takes in two parameters: an object and a type. The syntax is as follows:
1 |
isinstance(object, type) |
If the object belongs to the specified type or class, the function assesses to True; otherwise, it returns False. For illustration, consider the following:
1 2 |
num = 5 print(isinstance(num, int)) |
Step 2: Isinstance() with Multiple Types
Interestingly, Python allows you to check an object against multiple types concurrently. Instead of a single class/type as the second parameter, you can input a tuple consisting of the various types, like so:
1 2 |
num = 5 print(isinstance(num, (int, float, str))) |
Step 3: Using Isinstance() with Custom Classes
Besides Python’s inbuilt types, isinstance() equally supports custom class objects. This is especially useful when dealing with object-oriented programming in Python.
1 2 3 4 5 6 7 8 9 |
class Fruit: pass class Apple(Fruit): pass green_apple = Apple() print(isinstance(green_apple, Apple)) print(isinstance(green_apple, Fruit)) |
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# Step 1 num = 5 print(isinstance(num, int)) # Step 2 num = 5 print(isinstance(num, (int, float, str))) # Step 3 class Fruit: pass class Apple(Fruit): pass green_apple = Apple() print(isinstance(green_apple, Apple)) print(isinstance(green_apple, Fruit)) |
Output
True True True True
Conclusion
In conclusion, the isinstance() function is a powerful Python built-in tool for verifying an object’s type or class. By checking against a specific type or multiple classes, it becomes a handy companion for conditional programming, validation, and error handling. The function’s applicability further extends to custom class objects, enhancing its versatility.
This comprehensive tutorial should equip you to effectively use isinstance() in your Python programming. Keep practicing and exploring its various implementations to sharpen your programming skills. Happy coding!