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 Dictionary keys()
Python Set symmetric_difference_update()
Python Program to Display Calendar
Python String maketrans()
Python String isspace()
Python Program to Delete an Element From a Dictionary
Python print()
Python Program to Iterate Through Two Lists in Parallel
Python String startswith()
Python *args and **kwargs
Python Namespace and Scope
Python Variables, Constants and Literals
Python Set intersection_update()
Python Program to Check Whether a String is Palindrome or Not
Python Program to Shuffle Deck of Cards
Python Program to Multiply Two Matrices
Python Program to Find the Size (Resolution) of a Image
Python Functions
Python Set isdisjoint()
Python Program to Find Sum of Natural Numbers Using Recursion
Python Custom Exceptions
Python Program to Add Two Matrices
Python Program to Find ASCII Value of Character
Python break and continue
Python Set copy()
Python Program to Check the File Size
Python Dictionary setdefault()
Python super()
Python Dictionary pop()
Python iter()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Deep Learning Cookbook - Indra den Bakker