Proving Python Self Identity
Introduction: From "Trust Me" to "Prove It"
Welcome back to Understanding "self" in Python! With the first unit behind us, we already know the rule: self is the object that appears before the dot. So far, though, we have simply accepted that claim because the lesson said so.
This unit is about turning that claim into something we can verify with code using the smallest example possible. Two takeaways will guide us:
selfis an ordinary reference to the receiving object, and we can prove it with an identity check.- Because
selfpoints to one specific object, every object updates only its own data.
Our test subject will be a tiny class called Box, which we will build up one method at a time.
The Simplest Possible Method: One That Returns `self`
To study self, we want a method that does as little as possible. Nothing computed, no attributes read, and no text formatted: just hand back whatever self happens to be.
At first glance, me looks useless, and it would be in production code. As an experiment, however, it is perfect:
- The method declares one parameter,
self, exactly like the methods from the previous unit. - Its body performs no work at all; it returns the parameter untouched.
- Therefore, whatever value comes out of the call is precisely what
selfwas inside the call.
In other words, me is a window into the method's first argument. Instead of describing self, we can now inspect it directly.
The Identity Test: Proving self Is the Receiving Object
Let us create two boxes, give each one an items counter, and look through that window. As you may recall from the earlier course, is asks a strict question: Are these two names pointing at the exact same object in memory?
Reading the three checks in order:
a.me() is a: The call returns whatever sat before the dot, which isa, so the comparison isTrue.a.me() is b: The returned object is stilla, andaandbare two separate boxes, so this isFalse.b.me() is b: The same experiment with the other object confirms the pattern.
The conclusion is worth stating plainly: self is not a copy of the object, not a placeholder, and not the class. It is a reference to the one object that appeared before the dot.
