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 format()
Python id()
Python Program to Count the Number of Digits Present In a Number
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Program to Make a Simple Calculator
Python Program to Find the Factors of a Number
Python Set clear()
Python ord()
Python Program to Check Whether a String is Palindrome or Not
Python Program to Append to a File
Python Dictionary popitem()
Python Program to Solve Quadratic Equation
Python Program to Check the File Size
Python Program to Generate a Random Number
Python Tuple index()
Python Errors and Built-in Exceptions
Python Program to Parse a String to a Float or Int
Python String isalpha()
Python Keywords and Identifiers
Python sum()
Python min()
Python Program to Capitalize the First Character of a String
Python List Comprehension
Python divmod()
Python all()
Python timestamp to datetime and vice-versa
Python type()
Python Program to Measure the Elapsed Time in Python
Python Program to Check if a Number is Positive, Negative or 0
Python Set symmetric_difference_update()
Python String join()
Python List index()