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 List
Python str()
Python globals()
Python round()
Python Program to Compute all the Permutation of the String
Python Program to Transpose a Matrix
Python Tuple
Python Program to Illustrate Different Set Operations
Python Set add()
Python Numbers, Type Conversion and Mathematics
Python oct()
Python String partition()
Python Variables, Constants and Literals
Python ascii()
Python String isalpha()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Program to Iterate Over Dictionaries Using for Loop
Python Set difference_update()
Python Program to Find Numbers Divisible by Another Number
Python Set intersection()
Python String expandtabs()
Python if...else Statement
Python Program to Split a List Into Evenly Sized Chunks
Python Deep Learning Cookbook - Indra den Bakker
APIs in Node.js vs Python - A Comparison
Python List clear()
Python Strings
Python String join()
Python datetime
Python Directory and Files Management
Python Exception Handling Using try, except and finally statement
Python Program to Remove Duplicate Element From a List