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 enumerate()
Python zip()
Python Program to Safely Create a Nested Directory
Python Program to Differentiate Between del, remove, and pop on a List
Python Program to Sort a Dictionary by Value
Python List pop()
Python Custom Exceptions
Python Program to Find ASCII Value of Character
Python Program to Remove Punctuations From a String
Python Dictionary clear()
Python Program to Slice Lists
Python Program to Calculate the Area of a Triangle
Python sorted()
Python Program to Merge Two Dictionaries
Python timestamp to datetime and vice-versa
Python chr()
Python Program to Split a List Into Evenly Sized Chunks
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python complex()
Python any()
Python Program to Generate a Random Number
Python Program to Transpose a Matrix
Python Machine Learning - Sebastian Raschka
Python map()
Python Sets
Python hash()
Python Program to Concatenate Two Lists
Python Program to Find the Largest Among Three Numbers
Python String rindex()
Python print()
Python Program to Count the Occurrence of an Item in a List
Python Program to Extract Extension From the File Name