Test subclass relationships with issubclass().
How It Works
issubclass(candidate_class, classinfo) reports whether one class derives from another, including when both are the same class. It takes classes rather than normal instances.
Abstract base classes may customize subclass checks through registered virtual subclasses.
Step-by-Step Example
class Animal:
pass
class Cat(Animal):
pass
print(issubclass(Cat, Animal))
print(issubclass(Animal, Cat))
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The class groups related state and methods so each instance can manage its own values.
A successful run of this example prints the following output:
True
False
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Create a small three-level inheritance chain and test its relationships.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Passing an instance where issubclass expects a class as its first argument.
- Assuming a class cannot be considered a subclass of itself by issubclass().
Key Takeaways
- Test subclass relationships with issubclass().
- issubclass(candidate_class, classinfo) reports whether one class derives from another, including when both are the same class.
- Abstract base classes may customize subclass checks through registered virtual subclasses.