Confirm with isinstance()
In this step, you'll learn how to use the isinstance()
function in Python to check if an object is an instance of a particular class or type. This is another way to verify the data type of a variable, and it can be especially useful when working with inheritance and custom classes.
Let's continue using the string_examples.py
file you've been working with. We'll add some code to demonstrate how isinstance()
works.
The isinstance()
function takes two arguments: the object you want to check and the class or type you want to check against. It returns True
if the object is an instance of the specified class or type, and False
otherwise.
Add the following lines to your string_examples.py
file:
## Checking with isinstance()
print(isinstance(string1, str))
print(isinstance(number, int))
print(isinstance(decimal, float))
print(isinstance(boolean, bool))
print(isinstance(string1, int))
Save the file. Now, let's run the script using the python
command in the terminal:
python ~/project/string_examples.py
You should see the following output:
Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.
This is a
multi-line string.
This is another
multi-line string.
<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
True
True
True
True
False
As you can see, isinstance(string1, str)
returns True
because string1
is a string. Similarly, isinstance(number, int)
returns True
because number
is an integer, and so on. However, isinstance(string1, int)
returns False
because string1
is not an integer.
isinstance()
can also be used with custom classes. For example:
class MyClass:
pass
obj = MyClass()
print(isinstance(obj, MyClass))
Add these lines to your string_examples.py
file and run it again:
python ~/project/string_examples.py
You should see the following output:
Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.
This is a
multi-line string.
This is another
multi-line string.
<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
True
True
True
True
False
True
Here, isinstance(obj, MyClass)
returns True
because obj
is an instance of MyClass
.
Using isinstance()
is a powerful way to check the type of an object in Python, especially when working with inheritance and custom classes. It allows you to write more robust and flexible code that can handle different types of data correctly.