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 partition()
Python Closures
Python Program to Find Hash of File
Python Program to Get File Creation and Modification Date
Python @property decorator
Python Set symmetric_difference()
Python delattr()
Python bool()
Python String index()
Python eval()
Python String isupper()
Python sleep()
Python Program to Compute the Power of a Number
Python timestamp to datetime and vice-versa
Python Set symmetric_difference_update()
Python Program to Merge Two Dictionaries
Machine Learning with Python for everyone - Mark E.Fenner
Python Program to Slice Lists
Python Dictionary popitem()
Python Program to Shuffle Deck of Cards
Python Program to Get a Substring of a String
Python __import__()
Python File I/O Operation
Python String rstrip()
Python List extend()
APIs in Node.js vs Python - A Comparison
Python format()
Deep Learning with Python - Francois Cholletf
Python Set difference()
Python Program to Check if a Key is Already Present in a Dictionary
Python exec()
Python Program to Print Colored Text to the Terminal