Mutating Objects Through Functions
Introduction: From Reading to Changing
Welcome back to Getting Started with Classes in Python! We are now at the third unit, and our toolkit is growing nicely: We can define a class, create independent instances, and hand those instances to plain functions.
Every function we wrote in the previous unit was read-only: It looked at attributes and returned a new value, leaving the dog exactly as it found it. This unit asks a sharper question: What if a function reaches in and changes an attribute? Does the caller see that change, or does the function work on a private copy? We will answer this question with three functions named have_birthday, rename, and replace, all built on this familiar setup:
A Function That Changes an Attribute
Dogs get older, so let's write a function whose entire job is to increase the age attribute by one:
Notice what is missing: There is no return statement, so the call have_birthday(rex) evaluates to None. We also never assign anything back to rex. And yet the printed age is 4, not 3. The useful work happened entirely inside the function body, on the line dog.age += 1. This is an augmented assignment on an attribute: Python reads the current value of dog.age, adds one, and stores the resulting value back into that specific attribute on the object.
Why the Change Sticks: The Same Object, Not a Copy
To understand why rex reflects the change, trace what Python actually does at each step of the call:
Step 1 — Before the call. rex is a name that points to a Dog object sitting in memory. That object has three attributes stored inside it, including age = 3.
Step 2 — The call happens. When Python executes have_birthday(rex), it does not create a fresh Dog to hand to the function. Instead, it creates a local name dog inside the function and points it at the exact same object that rex already points to. Two names, one object.
Step 3 — The attribute is modified. The line dog.age += 1 does not move any names around. It reaches into the object and overwrites the value stored at the age attribute, changing it from 3 to 4. Because rex and dog both point at that same object, the change is immediately visible from either name.
Step 4 — The function ends. The local name dog disappears. The object itself stays in memory, unaffected by the function ending, and rex still points to it — now with age = 4.


