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 strftime()
Python String isalnum()
Python String lower()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python for Loop
Python Program to Add Two Numbers
Python open()
Python dict()
Python exec()
Python Matrices and NumPy Arrays
Python Program to Count the Number of Digits Present In a Number
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Java Program to Implement the Program Used in grep/egrep/fgrep
Python Program to Find the Factors of a Number
Python Set remove()
Python Program to Count the Occurrence of an Item in a List
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python bytes()
Python chr()
Python Set pop()
Python break and continue
Python Program to Print the Fibonacci sequence
Python Program to Find ASCII Value of Character
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python String partition()
Python Iterators
Python ascii()
Python String find()
Python String isnumeric()
Python Decorators
Python globals()