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 complex()
Python Program to Create a Countdown Timer
Python Program to Reverse a Number
Python Global, Local and Nonlocal variables
Python List count()
Python hash()
Python open()
Python setattr()
Python __import__()
Python timestamp to datetime and vice-versa
Python input()
Python Sets
Python Program to Return Multiple Values From a Function
Python Program to Convert Celsius To Fahrenheit
Python object()
Machine Learning with Python for everyone - Mark E.Fenner
Python round()
Python float()
Python sum()
Python Program to Check Whether a String is Palindrome or Not
Python issubclass()
Python String translate()
Python Program to Get the Full Path of the Current Working Directory
Python ascii()
Node.js vs Python for Backend Development
Python String rindex()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Dictionary fromkeys()
Python Namespace and Scope
Python memoryview()
Python Program to Convert Bytes to a String
Python for Loop