Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 18

Object Instantiation and State Management

Recommended resources

Hello! Welcome to the final lesson in our module on Object-Oriented Programming.

In the last few lessons, you've learned to build a class (the blueprint), use the __init__ constructor to give it attributes (the data), and define methods to give it behavior (the actions). So far, we've mostly worked with a single object at a time, like one LibraryBook.

Today, we'll unlock the real power of classes. Your goal for this lesson is to create multiple instances of a class and manage their individual state. This means you'll see how one class blueprint can be used to create many independent objects, each with its own data and behavior.

Imagine you're designing a video game. You'd need a hero, a villain, and maybe an army of a hundred zombies. You wouldn't write separate code for each one. Instead, you'd define a single Character class and create many instances from it, each with its own name, health, and power.

Python OOP for Beginners: Creating Multiple Objects
This code snippet illustrates the core idea of today's lesson: defining one `Character` class and using it to create multiple, unique objects like a `hero`, a `villain`, and a whole list of `zombies`.

1. Instances: Unique Objects From a Single Blueprint

The first and most important concept to grasp is that every time you "instantiate" a class (create an object), you get a new, completely separate object. Even if you create two objects that look identical, they exist independently in your computer's memory.

Let's explore this with a great article from Real Python.

Object-Oriented Programming (OOP) in Python

The article 'Object-Oriented Programming (OOP) in Python' explains instantiation clearly. We'll focus on the section that demonstrates how to create and compare two separate objects.

Read the section titled 'How Do You Instantiate a Class in Python?'. Pay close attention to the example where two Dog objects are created and assigned to variables a and b. The key part is the result of a == b, which is False. This proves they are distinct objects.

The article showed that Python considers the two Dog objects to be different. This is because they occupy different locations in memory. Let's see a video demonstration of this.

Python OOP Tutorial 1: Classes and Instances

This short clip from Corey Schafer's 'Python OOP Tutorial' provides a visual confirmation of what you just read. He creates two Employee objects and prints them.

Watch from 02:06 to 02:55. Notice that when the two Employee instances are printed, the output shows two different memory addresses (the 0x... part). This is the same concept the Real Python article demonstrated.

Think of it this way: a class is like an architectural blueprint for a house. You can use that same blueprint to build two houses. They may look identical, but they are two separate physical structures on two different plots of land. You can paint one house blue without the other one changing color.



2. Initializing Multiple Instances with Unique Data

So, we have separate objects. How do we give them their own unique data? This is where the __init__ constructor you learned about becomes essential. When you create an instance, you pass arguments to the class, and Python passes them along to the __init__ method for that specific instance.

This allows you to set up the initial state of each object right when it's created.

Let's return to the Real Python article to see how this works.

Object-Oriented Programming (OOP) in Python

Now we'll look at how to pass different data to create unique objects.

Read the section 'Class and Instance Attributes'. Focus on the code where two Dog instances are created: miles = Dog("Miles", 4) and buddy = Dog("Buddy", 9). Then, observe how accessing their attributes (miles.name, buddy.name) yields different results.

Corey Schafer's video also provides an excellent walkthrough of this process, showing how to update the code to use __init__ to create two distinct employees.

Python OOP Tutorial 1: Classes and Instances

This clip shows the practical coding steps for using __init__ to create multiple instances, making the code much cleaner and more efficient.

Watch from 04:43 to 08:43. The video starts by showing a manual (and clumsy) way to set attributes. The important part is when the __init__ method is introduced to automatically set up the first, last, and pay attributes for each new employee instance.


Quick Practice

In your code editor, use the LibraryBook class from the previous lesson.

  1. Create two instances of LibraryBook:
    • One for the book "1984" by "George Orwell".
    • Another for "Brave New World" by "Aldous Huxley".
  2. Print the title attribute of the first book.
  3. Print the author attribute of the second book.

You should see that each print statement correctly outputs the data associated with that specific instance.



3. Managing Individual State with Methods

The final piece of the puzzle is understanding how methods interact with individual instances. Since miles and buddy are separate objects, calling a method on miles will only affect the data stored in miles. The buddy object will remain unchanged.

This is the essence of "managing individual state." Each object is responsible for its own data.

The following resource provides a crystal-clear example using a Car class.

Classes and Objects in Python • Python Land Tutorial

This article from Python Land gives a perfect demonstration of two objects maintaining separate states.

Read the section titled 'Creating Multiple Python Objects'. The author creates car1 and car2. They then call methods on car1 to change its speed. The crucial part is when they check car1.speed and car2.speed and show that only car1 was affected.

Let's apply this to our LibraryBook practice.

  1. Take the two LibraryBook instances you created earlier.
  2. Call the check_out() method on your "1984" book instance.
  3. Now, call the status() method on both book instances.

What do you expect to see? You should find that "1984" is reported as "on loan," while "Brave New World" is still "available." This confirms that each object manages its own is_checked_out state.



4. Practice Exercise: Build Your Own Car Class

To solidify everything you've learned in this module, let's complete a final practice exercise. This challenge asks you to define a Car class, create multiple instances, and display their unique states.

Object-Oriented Programming (OOP) in Python

This challenge from the Real Python article is a great way to test your understanding of classes, constructors, methods, and instances.

Scroll down to the 'Exercise' block within the 'Instance Methods' section. First, read the challenge description carefully. Then, try to write the Car class and the code to create and print the two instances in your own editor. Once you have a working solution, you can expand the 'solution' block in the article to compare your approach.



Conclusion

Congratulations on completing the module on Object-Oriented Programming! You've gone from basic variables and loops to designing your own custom data types with unique data and behaviors.

Key Takeaways:

  • A class is a blueprint; an instance is a unique object created from that blueprint.
  • You can create many instances from a single class (e.g., car1 = Car(), car2 = Car()).
  • Each instance is a separate object in memory and is independent of all other instances.
  • You use the __init__ constructor to pass unique data to each instance upon creation.
  • Calling a method on one instance only modifies the state (the attributes) of that specific instance.

This ability to model real-world entities as objects is a fundamental concept in modern programming and will be a valuable tool in your problem-solving toolkit.

Preview of the Next Lesson:
With this foundation in place, we are ready to dive into the core of algorithm analysis. Your goal is to prepare for technical interviews, and a critical skill is being able to evaluate the efficiency of your code. In the next lesson, you will learn why measuring algorithm efficiency is critical for large inputs, setting the stage for learning Big O notation.