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 Program to Iterate Over Dictionaries Using for Loop
Python Program to Multiply Two Matrices
Python help()
Python bytearray()
Python staticmethod()
Python Program to Get File Creation and Modification Date
Python Program to Transpose a Matrix
Python Program to Convert Two Lists Into a Dictionary
Python filter()
Python Program to Find HCF or GCD
Python Program to Find ASCII Value of Character
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Print the Fibonacci sequence
Python String isdigit()
Python Program to Solve Quadratic Equation
Python Dictionary values()
Python strptime()
Python Program to Display the multiplication Table
Python Program to Shuffle Deck of Cards
Python Program to Merge Mails
Python String swapcase()
Python range()
How to get current date and time in Python?
Python tuple()
Python List pop()
Python if...else Statement
Python Generators
Python String lstrip()
Python List index()
Python repr()
Python String center()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar