How to Check If an Object Is an Instance of a Class in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will explore classes and instances in Python and learn how to check if an object is an instance of a class. You'll start by creating a Dog class with class and instance attributes, then create instances of the Dog class and access their attributes.

You will then learn to use isinstance() for type checking and compare it with type() for exact matches. This will enable you to determine if an object belongs to a specific class or a subclass of that class, providing a deeper understanding of object-oriented programming in Python.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ObjectOrientedProgrammingGroup(["Object-Oriented Programming"]) python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("Classes and Objects") python/ObjectOrientedProgrammingGroup -.-> python/constructor("Constructor") python/ObjectOrientedProgrammingGroup -.-> python/inheritance("Inheritance") subgraph Lab Skills python/build_in_functions -.-> lab-559613{{"How to Check If an Object Is an Instance of a Class in Python"}} python/classes_objects -.-> lab-559613{{"How to Check If an Object Is an Instance of a Class in Python"}} python/constructor -.-> lab-559613{{"How to Check If an Object Is an Instance of a Class in Python"}} python/inheritance -.-> lab-559613{{"How to Check If an Object Is an Instance of a Class in Python"}} end

Explore Classes and Instances

In this step, you will learn about classes and instances in Python. Classes are like blueprints for creating objects, and instances are the actual objects created from those blueprints. Understanding classes and instances is fundamental to object-oriented programming in Python.

First, let's create a simple class called Dog.

  1. Open the VS Code editor in the LabEx environment.

  2. Create a new file named dog.py in the ~/project directory.

    ~/project/dog.py
  3. Add the following code to dog.py:

    ## Define a class called Dog
    class Dog:
        ## Class attribute
        species = "Canis familiaris"
    
        ## Instance attribute
        def __init__(self, name, age):
            self.name = name
            self.age = age

    Here, we define a class named Dog. The species is a class attribute, meaning it's shared by all instances of the Dog class. The __init__ method is a special method called a constructor. It's used to initialize the instance attributes name and age when a new Dog object is created.

  4. Now, let's create instances of the Dog class. Add the following code to the end of dog.py:

    ## Create instances of the Dog class
    buddy = Dog("Buddy", 9)
    miles = Dog("Miles", 4)
    
    ## Access instance attributes
    print(f"{buddy.name} is {buddy.age} years old.")
    print(f"{miles.name} is {miles.age} years old.")
    
    ## Access class attribute
    print(f"{buddy.name} is a {buddy.species}.")
    print(f"{miles.name} is a {miles.species}.")

    In this part, we create two instances of the Dog class: buddy and miles. We then access their instance attributes (name and age) and the class attribute (species) using the dot notation (.).

  5. To run the dog.py script, open a terminal in VS Code and execute the following command:

    python dog.py

    You should see the following output:

    Buddy is 9 years old.
    Miles is 4 years old.
    Buddy is a Canis familiaris.
    Miles is a Canis familiaris.

    This output confirms that you have successfully created instances of the Dog class and accessed their attributes.

Use isinstance() for Type Checking

In this step, you will learn how to use the isinstance() function in Python to check if an object is an instance of a particular class. This is a useful tool for ensuring that your code handles different types of objects correctly.

Building upon the Dog class from the previous step, let's create a new Python file to explore isinstance().

  1. Open the VS Code editor in the LabEx environment.

  2. Create a new file named type_check.py in the ~/project directory.

    ~/project/type_check.py
  3. Copy the Dog class definition from dog.py into type_check.py. Your type_check.py file should now look like this:

    class Dog:
        species = "Canis familiaris"
    
        def __init__(self, name, age):
            self.name = name
            self.age = age
  4. Now, let's add some code to use the isinstance() function. Add the following code to the end of type_check.py:

    ## Create instances of the Dog class
    buddy = Dog("Buddy", 9)
    miles = Dog("Miles", 4)
    
    ## Check if buddy is an instance of the Dog class
    print(isinstance(buddy, Dog))
    
    ## Check if miles is an instance of the Dog class
    print(isinstance(miles, Dog))
    
    ## Check if a string is an instance of the Dog class
    print(isinstance("Hello", Dog))

    Here, we create two instances of the Dog class, buddy and miles. We then use the isinstance() function to check if these instances are of type Dog. We also check if a string "Hello" is an instance of the Dog class.

  5. To run the type_check.py script, open a terminal in VS Code and execute the following command:

    python type_check.py

    You should see the following output:

    True
    True
    False

    The output shows that buddy and miles are indeed instances of the Dog class, while the string "Hello" is not.

Compare with type() for Exact Matches

In this step, you will learn how to use the type() function in Python and compare it with isinstance() for type checking. While isinstance() checks if an object is an instance of a class or its subclasses, type() returns the exact type of an object.

To illustrate the difference, let's create a subclass of the Dog class and then use both isinstance() and type() to check the type of instances.

  1. Open the VS Code editor in the LabEx environment.

  2. Modify the type_check.py file in the ~/project directory.

    ~/project/type_check.py
  3. Add a new class called GermanShepherd that inherits from the Dog class. Your type_check.py file should now look like this:

    class Dog:
        species = "Canis familiaris"
    
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    class GermanShepherd(Dog):
        def __init__(self, name, age, training_level):
            super().__init__(name, age)
            self.training_level = training_level

    Here, GermanShepherd is a subclass of Dog. It inherits the name and age attributes from the Dog class and adds a new attribute training_level.

  4. Now, let's add some code to use the isinstance() and type() functions. Add the following code to the end of type_check.py:

    ## Create instances of the Dog and GermanShepherd classes
    buddy = Dog("Buddy", 9)
    sparky = GermanShepherd("Sparky", 3, "Advanced")
    
    ## Check types using isinstance()
    print(f"buddy isinstance Dog: {isinstance(buddy, Dog)}")
    print(f"sparky isinstance Dog: {isinstance(sparky, Dog)}")
    print(f"sparky isinstance GermanShepherd: {isinstance(sparky, GermanShepherd)}")
    
    ## Check types using type()
    print(f"type(buddy) == Dog: {type(buddy) == Dog}")
    print(f"type(sparky) == Dog: {type(sparky) == Dog}")
    print(f"type(sparky) == GermanShepherd: {type(sparky) == GermanShepherd}")

    In this part, we create an instance of the Dog class (buddy) and an instance of the GermanShepherd class (sparky). We then use isinstance() and type() to check their types.

  5. To run the type_check.py script, open a terminal in VS Code and execute the following command:

    python type_check.py

    You should see the following output:

    buddy isinstance Dog: True
    sparky isinstance Dog: True
    sparky isinstance GermanShepherd: True
    type(buddy) == Dog: True
    type(sparky) == Dog: False
    type(sparky) == GermanShepherd: True

    The output shows that isinstance(sparky, Dog) returns True because sparky is an instance of the GermanShepherd class, which is a subclass of Dog. However, type(sparky) == Dog returns False because type(sparky) returns the exact type, which is GermanShepherd, not Dog.

Summary

In this lab, you explored the fundamentals of classes and instances in Python. You learned how to define a class, including class attributes and instance attributes initialized within the __init__ constructor.

You then created instances of the Dog class, assigning values to their specific attributes. Finally, you accessed both instance attributes (name, age) and the class attribute (species) using dot notation, demonstrating how to retrieve information associated with objects and their classes.