In Python, the type()
and isinstance()
methods are used to determine the type of an object. But they serve different purposes:
type()
type(object)
method, this will return the exact type of the object. It returns a type object which is a class of object itself.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()
object
: The actual object we pass to this method.classinfo
: The class name we wanted to check for that object.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
.
|
| |
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