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.
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.
Open the VS Code editor in the LabEx environment.
Create a new file named
dog.pyin the~/projectdirectory.~/project/dog.pyAdd 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 = ageHere, we define a class named
Dog. Thespeciesis a class attribute, meaning it's shared by all instances of theDogclass. The__init__method is a special method called a constructor. It's used to initialize the instance attributesnameandagewhen a newDogobject is created.Now, let's create instances of the
Dogclass. Add the following code to the end ofdog.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
Dogclass:buddyandmiles. We then access their instance attributes (nameandage) and the class attribute (species) using the dot notation (.).To run the
dog.pyscript, open a terminal in VS Code and execute the following command:python dog.pyYou 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
Dogclass 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().
Open the VS Code editor in the LabEx environment.
Create a new file named
type_check.pyin the~/projectdirectory.~/project/type_check.pyCopy the
Dogclass definition fromdog.pyintotype_check.py. Yourtype_check.pyfile should now look like this:class Dog: species = "Canis familiaris" def __init__(self, name, age): self.name = name self.age = ageNow, let's add some code to use the
isinstance()function. Add the following code to the end oftype_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
Dogclass,buddyandmiles. We then use theisinstance()function to check if these instances are of typeDog. We also check if a string "Hello" is an instance of theDogclass.To run the
type_check.pyscript, open a terminal in VS Code and execute the following command:python type_check.pyYou should see the following output:
True True FalseThe output shows that
buddyandmilesare indeed instances of theDogclass, 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.
Open the VS Code editor in the LabEx environment.
Modify the
type_check.pyfile in the~/projectdirectory.~/project/type_check.pyAdd a new class called
GermanShepherdthat inherits from theDogclass. Yourtype_check.pyfile 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_levelHere,
GermanShepherdis a subclass ofDog. It inherits thenameandageattributes from theDogclass and adds a new attributetraining_level.Now, let's add some code to use the
isinstance()andtype()functions. Add the following code to the end oftype_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
Dogclass (buddy) and an instance of theGermanShepherdclass (sparky). We then useisinstance()andtype()to check their types.To run the
type_check.pyscript, open a terminal in VS Code and execute the following command:python type_check.pyYou 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: TrueThe output shows that
isinstance(sparky, Dog)returnsTruebecausesparkyis an instance of theGermanShepherdclass, which is a subclass ofDog. However,type(sparky) == DogreturnsFalsebecausetype(sparky)returns the exact type, which isGermanShepherd, notDog.
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.



