Python issubclass()
Function
The issubclass() function checks if a class is a subclass of another class or a tuple of classes. It is used in object-oriented programming to verify inheritance relationships.
Syntax
issubclass(class, classinfo)
Parameters:
class
– The class you want to check.classinfo
– A class or a tuple of classes to check against.
Returns:
True
ifclass
is a subclass (direct or indirect) ofclassinfo
.False
otherwise.
Example 1: Basic Usage
class Animal:
pass
class Dog(Animal):
pass
print(issubclass(Dog, Animal))
True
Example 2: Indirect Subclass
class Animal:
pass
class Mammal(Animal):
pass
class Cat(Mammal):
pass
print(issubclass(Cat, Animal))
True
Why? Because Cat
→ Mammal
→ Animal
. So, Cat is an indirect subclass of Animal.
Example 3: Using Tuple
class Vehicle: pass
class Car(Vehicle): pass
print(issubclass(Car, (Vehicle, Animal)))
True
Returns True
if Car
is a subclass of any class in the tuple.
Example 4: Invalid Check
print(issubclass(5, int))
TypeError: issubclass() arg 1 must be a class
Note: You must pass a class as the first argument, not an instance.
Use Cases
- Validating object types in class hierarchies
- Conditional behavior in frameworks using inheritance
- Metaprogramming and decorators
Common Mistakes
- ❌ Passing an instance instead of a class:
issubclass(dog, Animal)
❌ - Instead, use:
isinstance(dog, Animal)
to check instances
Interview Tip
issubclass()
is often tested with isinstance()
. Know the difference: one checks classes, the other checks instances.
Summary
issubclass(A, B)
returnsTrue
if A is a subclass of B- Supports tuples of classes
- Raises
TypeError
if the first argument is not a class
Practice Problem
Create a class hierarchy with Shape
, Polygon
, and Triangle
. Use issubclass()
to check if Triangle
is a subclass of Shape
.
class Shape: pass
class Polygon(Shape): pass
class Triangle(Polygon): pass
print(issubclass(Triangle, Shape))
Expected Output:
True