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 getattr()
Python String join()
Python range()
Python Dictionary
Python Closures
Python Anonymous / Lambda Function
Python Program to Count the Number of Occurrence of a Character in String
Intelligent Projects Using Python - Santanu Pattanayak
Python List Comprehension
Python Sets
Python object()
Python Program to Get the File Name From the File Path
Python Set remove()
Python Dictionary clear()
Python Set symmetric_difference_update()
Python Deep Learning Cookbook - Indra den Bakker
Python tuple()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python String rindex()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Dictionary values()
Python any()
Python slice()
Python String translate()
Python time Module
Python dir()
Python ord()
Python List remove()
Python Program to Differentiate Between del, remove, and pop on a List
Python staticmethod()
Python Tuple index()
Python Statement, Indentation and Comments