![]() |
VOOZH | about |
isinstance() is a built-in Python function that checks whether an object or variable is an instance of a specified type or class (or a tuple of classes), returning True if it matches and False otherwise, making it useful for type-checking and ensuring safe operations in dynamic code. Example:
True True
Explanation:
isinstance(obj, classinfo)
Parameters:
Returns:
Raises: TypeError if classinfo is not a valid class or type.
Example 1: In this example, we use isinstance() to check if an integer and a list are instances of the int or str types.
True True True
Explanation:
Example 2: In this example, we check if an object is an instance of a specific class or its parent class.
True True
Explanation:
Example 3: In this example, we check if an object is an instance of a specific type, such as a Python string or a dictionary.
True True
Explanation:
Example 4: In this example, we check if an object is an instance of a class or its derived class.
True
Explanation: isinstance(obj.method(), str) returns True as obj.method() returns the string "Hello".
The following table highlights the differences between the isinstance() and type() methods, both used for type checking. Knowing when to use each helps write more efficient and reliable code.
isinstance() | type() |
|---|---|
| Syntax: isinstance(object, class) | Syntax: type(object) |
It checks if an object is of a specific class type | It returns the class type of an object |
It can check if the object belongs to a class and its subclasses | It cannot deal with inheritance |
| It is faster as compared to type() | It is slower than isinstance() |
| It returns either True or False | It returns the type of the object |
| It can check for multiple classes at a time | It cannot do this |
| Example: isinstance(10, (int, str)) | Example: type(10) |