Algorithm
-
Purpose:
type(): Used to get the type of an object.isinstance(): Used to check if an object is an instance of a particular class or a tuple of classes.
-
Syntax:
type(object): Returns the type of the object.isinstance(object, classinfo): ReturnsTrueif the object is an instance of the specified class or a tuple of classes.
-
Use Cases:
type()is primarily used for obtaining the type of an object, e.g.,type(5)returns<class 'int'>.isinstance()is used for checking whether an object is an instance of a particular class or any class in a tuple.
-
Example:
python -
# type() example x = 5 print(type(x)) # Output: <class 'int'> # isinstance() example y = "Hello" print(isinstance(y, str)) # Output: True -
Handling Inheritance:
type()checks the exact type of the object, whileisinstance()considers inheritance. If the object is an instance of a subclass,isinstance()returnsTrue.
-
Tuple of Classes:
isinstance()allows checking against a tuple of classes. If the object is an instance of any class in the tuple, it returnsTrue.
-
Dynamic Typing:
- Both functions work well with Python's dynamic typing, allowing flexibility in type checking.
-
Common Usage:
type()is commonly used for basic type checking.isinstance()is preferred when dealing with inheritance and checking against multiple possible types.
-
Performance:
type()is generally faster since it only needs to determine the exact type.isinstance()might be slightly slower due to the additional checks for inheritance.
-
Conclusion:
- Use
type()for straightforward type checking. - Use
isinstance()for more flexible type checking, especially when dealing with inheritance or checking against multiple types.
- Use
Code Examples
#1 Code Example- Difference between type() and instance()
Code -
Python Programming
class Polygon:
def sides_no(self):
pass
class Triangle(Polygon):
def area(self):
pass
obj_polygon = Polygon()
obj_triangle = Triangle()
print(type(obj_triangle) == Triangle) # true
print(type(obj_triangle) == Polygon) # false
print(isinstance(obj_polygon, Polygon)) # true
print(isinstance(obj_triangle, Polygon)) # true
Copy The Code &
Try With Live Editor
Output
True
False
True
True
False
True
True
Demonstration
Python Program to Differentiate Between type() and isinstance()