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:
Node.js vs Python for Backend Development
Python Set symmetric_difference()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Set isdisjoint()
Python Program to Capitalize the First Character of a String
Python List reverse()
Python Program to Print Output Without a Newline
Python Package
Python range()
Python Dictionary fromkeys()
Python Get Current time
Python Program to Get the Last Element of the List
Python Decorators
Python Program to Compute all the Permutation of the String
Python sum()
Python Program to Find HCF or GCD
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Program to Find the Largest Among Three Numbers
Python Set intersection()
Python Namespace and Scope
Python hasattr()
Python help()
Python Program to Access Index of a List Using for Loop
Python Program to Compute the Power of a Number
Python List copy()
Python String index()
Python String rjust()
Python Program to Print Colored Text to the Terminal
Python String lower()
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Program to Check If a List is Empty
Python String endswith()