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 Dictionary fromkeys()
Python Program to Find Factorial of Number Using Recursion
Python compile()
Python Program to Compute all the Permutation of the String
Python ord()
Python Program to Find HCF or GCD
How to get current date and time in Python?
Python round()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python String swapcase()
Python String startswith()
Python String isspace()
Python Tuple
Python abs()
Python Program to Measure the Elapsed Time in Python
Python Set symmetric_difference()
Python Program to Check if a Key is Already Present in a Dictionary
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Program to Get Line Count of a File
Python any()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python classmethod()
Python property()
Python Program to Get the File Name From the File Path
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program to Count the Number of Digits Present In a Number
Python Program to Split a List Into Evenly Sized Chunks
Python Package
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Print all Prime Numbers in an Interval
Python Program to Slice Lists