Python supports object-oriented programming and hence classes can be created using python. Sometimes, it is essential to know mid-program that which objects belong to which class.
isinstance() performs this function and hence makes our programming tasks easier.
Syntax : isinstance(obj, class)
obj : The object that need to be checked as a part of class or not.
class : class/type/tuple of class or type, against which object is needed to be checked.
Returns : True, if object belongs to the given class/type if single class is passed or any of the class/type if tuple of class/type is passed, else returns False. Raises a TypeError if anything other than mentioned valid class type.
Code #1 : Demonstrating the working of isinstance for native types.
Is test_int integer? : True Is test_int string? : False Is test_str string? : True Is test_list integer? : False Is test_list list? : True Is test_int integer or list or string? : True Is test_list string or tuple? : False
Code #2 : Demonstrating use of isinstance() with objects
Is obj1 instance of gfg1? : True Is obj2 instance of gfg2? : True Is obj1 instance of gfg2? : False Is obj2 instance of gfg1? : True
- type and isinstance in Python
- Difference between Method Overloading and Method Overriding in Python
- class method vs static method in Python
- Python | set() method
- Python | next() method
- Python | os.dup() method
- Python PIL | getpalette() Method
- Python | os.kill() method
- Python - PyTorch div() method
- Python | os.get_blocking() method
- Python - PyTorch log() method
- Python Pytorch ones() method
- Python: filecmp.cmp() method
- Python | range() method
- Python Pytorch eye() method
- Python | Numpy np.fft() method
- Python | os.WSTOPSIG() method
- Python | os.WIFSIGNALED() method
- Python | os.WIFCONTINUED() method
- Python | os.WIFSTOPPED() method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.