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 RegEx
Python Program to Find HCF or GCD
Python String join()
Python String isdigit()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Dictionary items()
Python property()
Python Generators
Python Operator Overloading
Python while Loop
Python strftime()
Python sum()
Python Iterators
Python List sort()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Statement, Indentation and Comments
Python strptime()
Python Program to Find the Factorial of a Number
Python Object Oriented Programming
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python String format()
Python String isprintable()
Python Program to Find ASCII Value of Character
Python Program to Randomly Select an Element From the List
Python Modules
Python List index()
Python Program to Check If a String Is a Number (Float)
Python Program to Convert Celsius To Fahrenheit
Intelligent Projects Using Python - Santanu Pattanayak
Python max()
Python Program to Sort a Dictionary by Value
Python Dictionary