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:
Intelligent Projects Using Python - Santanu Pattanayak
Python staticmethod()
Python Program to Find Sum of Natural Numbers Using Recursion
Python Program to Find ASCII Value of Character
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Dictionary fromkeys()
Python String isdecimal()
Python String isalnum()
Python Program to Find HCF or GCD
Python Program to Reverse a Number
Python open()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Program to Sort a Dictionary by Value
Python Set issubset()
APIs in Node.js vs Python - A Comparison
Python oct()
Python Program to Find the Factorial of a Number
Python Program to Display Powers of 2 Using Anonymous Function
Python Program to Print the Fibonacci sequence
Python memoryview()
Java Program to Implement the Program Used in grep/egrep/fgrep
Python Set copy()
Python Program to Get Line Count of a File
Python time Module
Python String title()
Python List reverse()
Python Sets
Python Deep Learning Cookbook - Indra den Bakker
Python ord()
Python String partition()
Python set()
Python Program to Find Hash of File