What are the differences between type and isinstance() in Python?
In Python, the type() and isinstance() methods are used to determine the type of an object. But they serve different purposes:
type()
- By using the
type(object)method, this will return the exact type of the object. It returns a type object which is a class of object itself. - It does not consider inheritance if an object is an instance of a subclass. This method will only return the subclass’s name, ignoring the superclass. See the following code:
class Animal:passclass Dog(Animal):passobj_of_dog = Dog()integer_variable = 10print("Checking the type of object from Dog class: ", type(obj_of_dog))print("Checking the type of object from integer: ", type(integer_variable))
Using this code, if we call the type(obj_of_dog) method, this will return <class ‘main.Dog’>. Let’s see this code in action:
In the code example above, we have created an object of the Dog class inherited by the Animal class, but by calling the type() method for that object, it returns the type of that object.
isinstance()
- This method will check for an object if that object is an instance of that specific class. This method accepts the following parameters and returns a boolean value:
object: The actual object we pass to this method.classinfo: The class name we wanted to check for that object.
- This method considers inheritance and allows one to check if an object belongs to a particular hierarchy.
class Animal:passclass Dog(Animal):passobj_of_dog = Dog()obj_of_animal = Animal()integer_variable = 10print("Checking the Dog object with Dog Class: ", isinstance(obj_of_dog, Dog))print("Checking the Dog object with Animal Class: ", isinstance(obj_of_dog, Dog))print("Checking the Animal object with Dog Class: ", isinstance(obj_of_animal, Dog))print("Checking the integer object with integer Class: ", isinstance(integer_variable, int))
If we call the isinstance() method and pass the instance of Dog and check if it’s an instance of Dog or the Animal class, this method will return the True.
Comparison
Comparison of type() and instance() method
|
| |
Return Type | Object of |
|
Hierarchy | Does not consider | Considers |
Inhertance | Does not consider | Considers |
class Animal:passclass Dog(Animal):passobj_of_dog = Dog()obj_of_animal = Animal()integer_variable = 10print("Checking the Dog object with Dog Class: ", isinstance(obj_of_dog, Dog))print("Checking the type of object from Dog class: ", type(obj_of_dog), "\n")print("Checking the Dog object with Animal Class: ", isinstance(obj_of_dog, Dog))print("Checking the type of object from Animal class: ", type(obj_of_animal))
In most cases, we want to use the isinstance() when we need to check if an object is an instance of a certain class or its subclasses, as it provides a more flexible and robust way to handle object types and class hierarchies.
Free Resources