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 Directory and Files Management
Python float()
Python Program to Print Output Without a Newline
Python String count()
Python input()
Python Set isdisjoint()
Python Matrices and NumPy Arrays
Python List reverse()
Python String islower()
Python slice()
Python Program to Randomly Select an Element From the List
Python Program Read a File Line by Line Into a List
Python Inheritance
Python type()
Python hasattr()
Python Set difference()
Python String index()
Python Program to Get the File Name From the File Path
Python Program to Find LCM
Python Program to Find Sum of Natural Numbers Using Recursion
Python filter()
Python Program to Print Colored Text to the Terminal
Python complex()
Python isinstance()
Python Set issubset()
Python Set intersection()
Python String capitalize()
Python Data Types
Python Program to Get the Last Element of the List
Python id()
Python Program to Get a Substring of a String
Python Program to Check Whether a String is Palindrome or Not