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 upper()
Python getattr()
Python String maketrans()
Python Program to Sort a Dictionary by Value
Python Program to Check Armstrong Number
Python int()
Intelligent Projects Using Python - Santanu Pattanayak
Python Program to Extract Extension From the File Name
Python Program to Find Armstrong Number in an Interval
Python Set update()
Node.js vs Python for Backend Development
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python List clear()
Python pass statement
Python Program to Get the Class Name of an Instance
Python Objects and Classes
Python Program to Print the Fibonacci sequence
Python Set pop()
Python Program to Sort Words in Alphabetic Order
Python delattr()
Python Tuple
Python Program to Convert Bytes to a String
Python Program to Count the Number of Occurrence of a Character in String
Python list()
Python dict()
Python Global, Local and Nonlocal variables
Python @property decorator
Python Matrices and NumPy Arrays
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python reversed()
Python Program to Print Colored Text to the Terminal
Python Program to Remove Duplicate Element From a List