Explaining the 'self' variable to a beginner
It may help you to think of the obj.method(arg1, arg2)
invocation syntax as purely syntactic sugar for calling method(obj, arg1, arg2)
(except that method
is looked up via obj
's type, and isn't global).
If you view it that way, obj
is the first argument to the function, which traditionally is named self
in the parameter list. (You can, in fact, name it something else, and your code will work correctly, but other Python coders will frown at you.)
I'll try to clear up some confusion about classes and objects for you first. Lets look at this block of code:
>>> class Bank(): # let's create a bank, building ATMs
... crisis = False
... def create_atm(self) :
... while not self.crisis :
... yield "$100"
The comment there is a bit deceptive. The above code does not "create" a bank. It defines what a bank is. A bank is something which has a property called crisis
, and a function create_atm
. That's what the above code says.
Now let's actually create a bank:
>>> x = Bank()
There, x
is now a bank. x
has a property crisis
and a function create_atm
. Calling x.create_atm();
in python is the same as calling Bank.create_atm(x);
, so now self
refers to x
. If you add another bank called y
, calling y.create_atm()
will know to look at y
's value of crisis, not x
's since in that function self
refers to y
.
self
is just a naming convention, but it is very good to stick with it. It's still worth pointing out that the code above is equivalent to:
>>> class Bank(): # let's create a bank, building ATMs
... crisis = False
... def create_atm(thisbank) :
... while not thisbank.crisis :
... yield "$100"