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 Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Program to Get a Substring of a String
Python Program to Split a List Into Evenly Sized Chunks
Python len()
Python Program to Sort a Dictionary by Value
Python Program to Count the Occurrence of an Item in a List
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python String rpartition()
Python List remove()
Python compile()
Python Program to Solve Quadratic Equation
Python Functions
Python hex()
Python String rstrip()
Python Program to Find the Largest Among Three Numbers
Python Program to Check Leap Year
Python Set update()
Python Dictionary keys()
Python Program to Represent enum
Python String ljust()
Python Strings
Python List count()
Python hasattr()
Python divmod()
Python issubclass()
Python id()
Python int()
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
How to Get Started With Python?
Python String zfill()