Python Program to Differentiate Between type() and isinstance()
In Python, type() and isinstance() are built-in functions used to check the type of an object. In summary, type() function returns the type of an object, while isinstance() function checks if an object is an instance of a particular class or not.
Python Code :
The Below Python program that demonstrates the difference between type() and isinstance():
# Define a simple class
class MyClass:
pass
# Create an instance of the class
my_object = MyClass()
# Check the type of the instance using the type() function
print(type(my_object) == MyClass) # prints True
# Check the type of the instance using the isinstance() function
print(isinstance(my_object, MyClass)) # prints True
# Check the type of the instance using the isinstance() function with a base class
print(isinstance(my_object, object)) # prints True
# Check the type of a string using the type() function
print(type("Hello, World!") == str) # prints True
# Check the type of a string using the isinstance() function
print(isinstance("Hello, World!", str)) # prints True
# Check the type of a string using the isinstance() function with a base class
print(isinstance("Hello, World!", object)) # prints True
In this program, we first define a simple class MyClass using the class keyword.
We then create an instance of the class by calling the class constructor and assigning the resulting object to the variable my_object.
To check the type of the instance, we use the type() function, which returns the type of an object. We compare the result of type(my_object) to the MyClass class using the == operator. We also check the type of the instance using the isinstance() function, which returns True if the object is an instance of the specified class or any of its subclasses. We pass my_object as the first argument and MyClass as the second argument to the isinstance() function.
We also demonstrate the use of the isinstance() function with a base class, which returns True if the object is an instance of the specified base class or any of its subclasses.
Finally, we demonstrate the difference between type() and isinstance() with a string. We check the type of the string using both functions, and also demonstrate the use of the isinstance() function with a base class. Note that in this case, the type() and isinstance() functions produce the same result, since a string is an instance of the str class and the object base class.