Building and Processing Objects
Introduction: From One Dog to a Whole Kennel
Welcome back to Getting Started with Classes in Python! This is the fourth and final unit of the course, and we are about to close two gaps that have been quietly sitting in our toolkit.
First, every object so far was built by hand: We created an empty instance and then attached each attribute on its own line. No function has ever created an object for us. Second, we have always worked with one dog at a time, while real programs juggle dozens or thousands of objects at once.
This unit fixes both problems with four moves: a factory function that builds and returns a ready object, a list that holds many objects, a function that aggregates data across that list, and a function that selects and returns one object from it. The class itself stays as bare as ever:
The Factory Function: Building an Object and Returning It
Instead of writing three assignment lines every time we need a dog, let's put that work into a function that hands us a finished object:
The body follows a simple four-step shape: create the empty instance, copy each parameter into the matching attribute, and then return the result. Notice that dog = Dog() is exactly the rebinding we warned about in the previous unit, but here it is intentional and harmless: The function creates the object itself, and the return statement makes sure the caller receives it. Because rex captures that return value, nothing gets lost. As a bonus, every dog built this way is guaranteed to carry the same three attributes.
Note: In the next courses, we'll learn how to build objects even more conveniently. However, factory functions similar to make_dog are also used in real products sometimes!
Storing Many Objects in a List
A Python list does not care what kind of values it holds, so it can store Dog objects just as happily as numbers or strings. This is where the factory really pays off:
Each of the three calls runs, builds a separate Dog, and returns it; the list simply collects those three returned objects in order. Every element is an independent instance with its own attribute values, exactly like the separate dogs from Unit 1. To reach data inside one of them, we combine indexing with dot notation: kennel[0] gives us the first Dog, and .name reads its attribute. Without make_dog, this same list would have taken twelve lines of setup.
