Course contentsShow
← Python
Lesson 444 of 1,0607. Object-Oriented ProgrammingFree lesson

Checking Type Relationships with Isinstance

You will use the isinstance and issubclass functions to dynamically verify the inheritance lineage of objects during program execution.

Checking Type Relationships with Isinstance

In this lesson, you will learn how to verify an object's lineage and identify its type dynamically using the isinstance() and issubclass() functions.

Why Check Types?

As you build complex inheritance hierarchies, it becomes crucial to know exactly what kind of object you are dealing with before performing operations on it. Python provides two built-in functions that allow your code to inspect its own structure at runtime.

The isinstance() Function

The isinstance(object, class) function checks if a specific object is an instance of a given class, or an instance of any class derived from it. This is the preferred way to check types in Python because it respects inheritance.

class Animal:
    pass

class Dog(Animal):
    pass

my_dog = Dog()

# Returns True because Dog inherits from Animal
print(isinstance(my_dog, Animal))  # Output: True
print(isinstance(my_dog, Dog))     # Output: True

The issubclass() Function

While isinstance checks an object, issubclass(class1, class2) checks the relationship between two classes. It returns True if class1 is a subclass of class2.

# Returns True because Dog is a child of Animal
print(issubclass(Dog, Animal))     # Output: True
print(issubclass(Animal, Dog))     # Output: False

Dynamic Verification

Using these tools, you can write "defensive" code that behaves differently depending on the class hierarchy. For example, if you have a function that processes various animals, you can use isinstance to ensure the object provided supports the expected interface or behavior before interacting with it. This prevents errors when your program encounters unexpected types within a polymorphic structure.

By leveraging these checks, your applications can remain flexible while maintaining strict control over the objects being passed around, ensuring that your logic executes only on compatible types.

Key Takeaway: Use isinstance() to check if an object belongs to a class hierarchy, and issubclass() to verify the relationship between classes themselves, allowing your code to safely navigate complex inheritance structures.