Initializing Objects Automatically
Introduction: Objects That Arrive Ready to Use
Welcome to the final unit of Understanding "self" in Python! Returning to our Dog example: every object was born empty, and we had to attach name, breed, and age line by line before any method would work. Forget one line, and the next method call raises an AttributeError.
Python has a built-in fix for exactly this: a method that runs automatically the moment an object is created, so the object is complete before we ever touch it. Before we get there, though, we will build the setup by hand, which will also show us exactly how a value passed in becomes an attribute stored on the object.
By the end you will be able to:
- Write a method that assigns attributes through
self. - Turn that method into an
__init__that runs automatically. - Give parameters default values so some arguments become optional.
From Repeated Lines to a Setup Method
Here is the setup we have been using in our examples:
Four lines just to get one usable dog, and every one of them is a chance to forget something. The natural move is to bundle those assignments into a method and call it once. Let us write a method called construct that takes the values as parameters:
Now the setup shrinks to two lines:
Look closely at a single line inside the method: self.name = new_name. There are two different things here:
new_nameis the parameter, a temporary label holding the value"Rex"that the caller passed in. It exists only while the method runs, then disappears.self.nameis an attribute stored on the object. The dot means "reach intoselfand set itsname." This one survives after the method ends.
So the line reads: take the value sitting in the parameter new_name, and store it in the object's own name attribute. The value moves from a throwaway parameter into a permanent home on the object.
Reusing the Parameter Name
Because self.name and new_name are genuinely different things, the new_ prefix was only ever a teaching aid. Python does not require the parameter to have a distinct name; the dot on self.name already sets it apart. So we can drop the prefix and call the parameter simply name:
This is the version you will see everywhere, so it is worth reading slowly. In self.name = name:
- The right-hand side,
name, is the parameter, the value passed in. - The left-hand side,
self.name, is the attribute on the object.
They look almost identical, but the dot changes everything. self.name lives on the object and lasts; name is a local parameter that vanishes when the method finishes. The line copies the value from one into the other. The two sides are not the same variable, they just happen to share a spelling.
