2.1.5 · D3OOP Fundamentals

Worked examples — `self` — what it is and how Python passes it

2,175 words10 min readBack to topic

This page hunts down every way self can show up in real code and drags each one into the light. If you have not yet seen what self is, read the parent first: self — the parent note and the machinery in Bound and Unbound Methods.


The scenario matrix

Before any code, let's list every case class a self question can belong to. Each worked example below is tagged with the cell it fills.

# Cell (the scenario) What makes it tricky
A Two instances, one body proving states stay separate
B Manual pass through the class Class.m(obj) vs obj.m()
C Method returns self chaining / fluent APIs
D self reassigned inside a method rebinding the local name does nothing outside
E self renamed (this, me) proving it's a convention
F Degenerate: no self in signature the TypeError and its off-by-one arg count
G Degenerate: passing self twice obj.m(obj) too-many-args
H Bound-method object stored/passed alice.deposit as a first-class value
I Word problem (real world) translate English → which self
J Exam twist: classmethod / staticmethod when there is no self at all

We now cover A → J with 9 examples. Related landmarks: Classes and Instances, __init__ — the constructor, Instance vs Class Attributes, Descriptor Protocol, classmethod and staticmethod.

Figure — `self` — what it is and how Python passes it

The figure above is the whole page in one picture: the red arrow is the dot handing the object into the first slot. Keep it in your eye.


Worked examples









Figure — `self` — what it is and how Python passes it

Active recall

Recall Does rebinding

self = something inside a method change the caller's object? No. It only re-points the local name self; the caller's object is untouched (Ex 4).

Recall Is

f is alice.deposit True? No — each attribute access builds a fresh bound-method object, so it's False (Ex 8).

Recall In a

classmethod, what fills the first slot instead of the instance? cls, the class itself — not any instance (Ex 9).

Recall Why does

alice.deposit(alice, 50) fail? The dot already injected alice, so you passed it twice → too many arguments (Ex 7).


Connections

Concept Map

fills slot

instance method

classmethod

staticmethod

Ex 1 to 8

Ex 9

Ex 9

obj.method args

first parameter slot

self is the instance

cls is the class

nobody injected

separate states, chaining, bound methods

shared class data

plain helper function