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 super()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Program to Find Armstrong Number in an Interval
Python Program to Display Fibonacci Sequence Using Recursion
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Compute the Power of a Number
Python String endswith()
Python pow()
Python Functions
Python oct()
Python List
Python Generators
Python Program to Make a Simple Calculator
Python Recursion
Python strptime()
Python Program to Remove Punctuations From a String
Python String maketrans()
Python Decorators
Python sum()
Python Exception Handling Using try, except and finally statement
Python String rjust()
Python bin()
Python Program to Print Colored Text to the Terminal
Python String lower()
Python String rfind()
Python String isnumeric()
Python Objects and Classes
Python input()
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Find Sum of Natural Numbers Using Recursion
Python Program to Sort Words in Alphabetic Order
Node.js vs Python for Backend Development