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"