In this example, you will learn to differentiate between type() and isinstance().
To understand this example, you should have the knowledge of the following Python programming topics:
Difference between type() and instance()
Let’s understand the difference between type() and instance() with the example code below.
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
Output
True False True True
In the above example, we see that type() cannot distinguish whether an instance of a class is somehow related to the base class. In our case, although obj_triangle is an instance of child class Triangle, it is inherited from the base class Polygon. If you want to relate the object of a child class with the base class, you can achieve this with instance().
Related posts:
Python min()
Python Program to Check if a Key is Already Present in a Dictionary
Python Program to Measure the Elapsed Time in Python
Python Program to Check Armstrong Number
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python isinstance()
Python Program to Find the Square Root
Python Dictionary copy()
Python String isupper()
Python compile()
Python List
Python Operators
Python List extend()
Python print()
Python String format()
Python vars()
Python Matrices and NumPy Arrays
Python List append()
Python String join()
Python Objects and Classes
Python callable()
Python Global, Local and Nonlocal variables
Python Program to Illustrate Different Set Operations
Python Program to Add Two Matrices
Python Program to Print Colored Text to the Terminal
Python Sets
Python String rpartition()
Python Program to Reverse a Number
Python ascii()
Python Program to Delete an Element From a Dictionary
How to Get Started With Python?
Python Tuple count()