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 print()
Python ascii()
Python String casefold()
Python Program to Create Pyramid Patterns
Python @property decorator
Python Program to Catch Multiple Exceptions in One Line
Python Program to Print all Prime Numbers in an Interval
Python Program to Check if a Number is Odd or Even
Python String format()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python String find()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Function Arguments
Python Program to Solve Quadratic Equation
Python Anonymous / Lambda Function
Python Program to Trim Whitespace From a String
Python setattr()
Python break and continue
Python Machine Learning - Sebastian Raschka
Python Program to Get File Creation and Modification Date
Python String isdecimal()
Python Numbers, Type Conversion and Mathematics
Python Set pop()
Deep Learning with Python - Francois Chollet
Python List reverse()
Python Package
Python Object Oriented Programming
Python dict()
Python String upper()
Python frozenset()
Python Operators
Python Shallow Copy and Deep Copy