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 String format()
Python Dictionary get()
Python frozenset()
Python RegEx
Python input()
Python Program to Remove Punctuations From a String
Python round()
Python Deep Learning Cookbook - Indra den Bakker
Python List clear()
Python min()
Python File I/O Operation
Python Program to Find HCF or GCD
How to get current date and time in Python?
Python List Comprehension
Python List count()
Python Program to Check the File Size
Python Program to Merge Mails
Python Get Current time
Python Program to Concatenate Two Lists
Python Program to Convert Decimal to Binary Using Recursion
Python Program to Check Prime Number
Python Program to Find Armstrong Number in an Interval
Python Program to Get the Last Element of the List
Python String capitalize()
Python Program to Make a Simple Calculator
Python Program to Compute all the Permutation of the String
Python String partition()
Python break and continue
Python Program to Swap Two Variables
Python __import__()
Python frozenset()
Python String title()