isinstance and issubclass
- Python course
- Intermediate
- Lesson 11/116
- 5 min
Learn type checks with isinstance and issubclass.
The isinstance function
isinstance(obj, Class) checks whether an object is an instance of a class (or its subclasses). It returns True or False.
Example: isinstance(d, Dog). If d is a Dog instance it returns True. If Dog inherits from Animal, then isinstance(d, Animal) also returns True. It accounts for the inheritance chain.
The issubclass function
issubclass(Child, Parent) checks whether a class is a subclass of another. It also returns True or False.
Example: issubclass(Dog, Animal). If Dog inherits from Animal it returns True. Here classes, not instances, are compared. isinstance is for instances; issubclass is for classes.
Practice Try isinstance and issubclass
First define the Animal class (body pass). Then define class Dog(Animal): pass. Create an instance with d = Dog(). Write three lines: print(isinstance(d, Dog)), print(isinstance(d, Animal)) and print(issubclass(Dog, Animal)).
Starter code
# Define the Animal and Dog classesSample solution
# Define the Animal and Dog classes
class Animal:
pass
class Dog(Animal):
pass
d = Dog()
print(isinstance(d, Dog))
print(isinstance(d, Animal))
print(issubclass(Dog, Animal))Expected output
True True True
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does isinstance(d, Dog) return?
- None
- False
- True Correct answer
- Dog
Explanation: If d is a Dog instance, it returns True.
2 Match the functions
| Term | Meaning |
|---|---|
isinstance |
Is instance? |
issubclass |
Is subclass? |
type |
Exact type |
3 Complete the isinstance call
if isinstance(d, ____):
print("Dog")
if isinstance(d, Dog):
print("Dog")
Explanation: The Dog class name starts with an uppercase letter.