Python: isinstance() function
isinstance() function
The isinstance() function returns true if the object argument is an instance of the classinfo argument, or of a subclass thereof.
If object is not an object of the given type, the function always returns false. If classinfo is a tuple of type objects return true if object is an instance of any of the types.
If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.
Version:
(Python 3.2.5)
Syntax:
isinstance(object, classinfo)
Parameter:
Name | Description | Required / Optional |
---|---|---|
object | An object. | Required |
classinfo | A type or a class, or a tuple of types and/or classes. |
Optional |
Example: Python isinstance() function
num = [2, 4, 6]
x = isinstance(num, list)
print(num,'Instance of list?', x)
x = isinstance(num, dict)
print(num,'Instance of dict?', x)
x = isinstance(num, (dict, list))
print(num,'Instance of dict or list?', x)
number = 7
x = isinstance(num, list)
print(num,'Instance of list?', x)
x = isinstance(num, int)
print(num,'Instance of int?', x)
Output:
[2, 4, 6] instance of list? True [2, 4, 6] instance of dict? False [2, 4, 6] instance of dict or list? True [2, 4, 6] instance of list? True [2, 4, 6] instance of int? False
Python Code Editor:
Previous: int()
Next: issubclass()
Test your Python skills with w3resource's quiz
Python: Tips of the Day
Find current directory and file's directory:
To get the full path to the directory a Python file is contained in, write this in that file:
import os dir_path = os.path.dirname(os.path.realpath(__file__))
(Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)
To get the current working directory use
import os cwd = os.getcwd()
Documentation references for the modules, constants and functions used above:
- The os and os.path modules.
- The __file__ constant
- os.path.realpath(path) (returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")
- os.path.dirname(path) (returns "the directory name of pathname path")
- os.getcwd() (returns "a string representing the current working directory")
- os.chdir(path) ("change the current working directory to path")
Ref: https://bit.ly/3fy0R6m
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework