Isinstance() Function in Python
In Python, the isinstance()
function is used to check if an object is an instance of a specific class.
Syntax
isinstance(object, class)
The function takes two parameters:
- The object you want to check.
- The class you want to verify against.
It returns a boolean value:
- True: If the object is an instance of the specified class.
- False: If the object is not an instance of the specified class.
A Practical Example
Here’s a simple script where I define two classes.
I then create an instance of the first class (Classe1
) and assign it to the variable var
.
- class Classe1(object):
- def metodo1(self):
- print('A')
- class Classe2(object):
- def metodo1(self):
- print('B')
- var = Classe1()
Next, I use the isinstance() function to determine if var
is an instance of Classe1
.
The function returns True as expected:
>>> isinstance(var, Classe1)
>>> True
This confirms that var
is indeed an instance of Classe1
.
Now, let’s check if var
is an instance of the second class, Classe2
.
>>> isinstance(var, Classe2)
>>> False
Here, the function returns False, as var
is not an instance of Classe2
.
And so on.