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 classmethod()
Python Function Arguments
Python String endswith()
Python *args and **kwargs
Python bytearray()
Python Program to Check the File Size
Python chr()
Debug a JavaMail Program
Python Program to Count the Occurrence of an Item in a List
Python Program to Concatenate Two Lists
Python List sort()
Python Program to Iterate Through Two Lists in Parallel
Python Program to Swap Two Variables
Python List pop()
Python pow()
Python exec()
Python Dictionary
Python ord()
Python Program to Convert Two Lists Into a Dictionary
Python compile()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Program to Return Multiple Values From a Function
Python range()
Python String casefold()
Python Program to Check If Two Strings are Anagram
Python divmod()
Python Program to Capitalize the First Character of a String
Python Dictionary fromkeys()
How to get current date and time in Python?
Python hash()
Python super()
Python while Loop