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 Object Oriented Programming
Python Global, Local and Nonlocal variables
Python Decorators
Python bool()
Python Program to Find Armstrong Number in an Interval
Python String isnumeric()
Python Program to Get Line Count of a File
Deep Learning with Python - Francois Chollet
Python List sort()
Python Custom Exceptions
Python Keywords and Identifiers
Python Program to Return Multiple Values From a Function
Python Set discard()
Machine Learning with Python for everyone - Mark E.Fenner
Python Data Types
Python issubclass()
Python Program to Print Colored Text to the Terminal
Python object()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Extract Extension From the File Name
Python next()
Python Program to Find Numbers Divisible by Another Number
Python vars()
Python __import__()
Python bytearray()
Python String ljust()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python slice()
Python filter()
Python Errors and Built-in Exceptions
Python Program to Reverse a Number
Python chr()