Overview:
- The built-in function isinstance() checks whether an object is an instance of one or more given types and returns True if the object is an instance of the one of the types given. It returns False, if the instance is not of any of the types given.
- For example, a digital pen can be classified as both a writing instrument and a digital pen. An eraser can neither be classified as a writing instrument nor a digital pen.
Example 1:
# Example Python program that checks class Pencil(WritingInstrument): # Create a FountainPen instance isWriter = isinstance(pen, Pencil) isWriter = isinstance(pen, FountainPen) isWriter = isinstance(pen, WritingInstrument) |
Output:
FountainPen writing A pen is a pencil:False A fountain pen is a FountainPen:True A pen is a writing instrument:True |
Example 2 - Checking an object is an instance of more than one type:
class DigitalPen(WritingInstrument): digiPen = DigitalPen() isWriter = isinstance(digiPen, FountainPen) |
Output:
A digital pen is a digital pen and also an writing instrument:True A digital pen is a fountain pen:False |
Example 3 - Checking an object is an instance of virtual base class:
# Example Python program that instantiates a virtual subclass from abc import ABC # WritingInstrument interface # Independent DeviceSpecificStylus not implementing the # Developer decides DeviceSpecificStylus is a perfect stylus = DeviceSpecificStylus() |
Output:
stylus is an instance of WritingInstrument: True |
Example 4 - Checking an object is an instance of an indirect base class:
class MechanicalPencil(Pencil): mechPencil = MechanicalPencil() |
Output:
A digital pen is a fountain pen:False mechPencil is an instance of WritingInstrument:True |