What are the differences between type() and isinstance()?
In Python, type() is a built-in function that returns the type of an object, while isinstance() is a function that checks whether an object is an instance of a particular class or of a subclass thereof.
In Python, type() is a built-in function that returns the type of an object, while isinstance() is a function that checks whether an object is an instance of a particular class or of a subclass thereof.
Here's an example of how to use these functions:
Python isinstance and type functions example
class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
print(type(dog)) # Output: <class '__main__.Dog'>
print(isinstance(dog, Dog)) # Output: True
print(isinstance(dog, Animal))# Output: True (checks subclasses)
print(type(dog) == Animal) # Output: False (type() does not check inheritance)The type() function returns the type of the object as a type object (for example, int, float, str, etc.). On the other hand, isinstance() checks the object's type and returns True if it is an instance of the specified class or a subclass thereof, and False otherwise.
One important distinction is that type() only matches the exact class, ignoring inheritance, while isinstance() correctly handles subclass relationships. This makes isinstance() the preferred choice for type checking in most practical scenarios, especially when working with inheritance hierarchies. Use type() only when you need to verify the exact class without considering subclasses.
I hope this helps! Let me know if you have any questions.