This question already has an answer here:
- What is the purpose of self? 19 answers
I'm pretty much ignorant of OOP jargon and concepts. I know conceptually what an object is, and that objects have methods. I even understand that in python, classes are objects! That's cool, I just don't know what it means. It isn't clicking with me.
I'm currently trying to understand a few detailed answers that I think will illuminate my understanding of python:
In the first answer, the author uses the following code as an example:
>>> class Bank(): # let's create a bank, building ATMs
... crisis = False
... def create_atm(self) :
... while not self.crisis :
... yield "$100"
I don't immediately grok what self
is pointing to. This is definitely a symptom of not understanding classes, which I will work on at some point. To clarify, in
>>> def func():
... for i in range(3):
... print i
I understand that i
points to an item in the list range(3)
which, since it is in a function, isn't global. But what does self
"point to"?
self
is an argument passed in to the function. In Python, this first argument is implicitly the object that the method was invoked on. In other words:These last two lines have equivalent behavior. (Unless
bar
refers to an object of a subclass ofBar
-- thensomeMethod()
might refer to a different function object.)Note that you can name the "special" first argument anything you want --
self
is just a convention for methods.The name
self
does not exist in the context of that function. Attempting to use it would raise aNameError
.Example transcript:
"self" is the instance object automatically passed to the class instance's method when called, to identify the instance that called it. "self" is used to access other attributes or methods of the object from inside the method. (methods are basically just functions that belong to a class)
"self" does not need to be used when calling a method when you already have an available instance.
Accessing the "some_attribute" attribute from inside a method:
Accessing the "some_attribute" attribute from an existing instance:
Here is a little code to demonstrate that self is the same as the instance:
As mentioned by others, it's named "self" by convention, but it could be named anything.
One Rubyist's perspective (Ruby is my first programming language so I apologize for whatever oversimplified, potentially wrong abstractions I'm about to use)
as far as I can tell, the dot operator, for example:
is such that
os
gets passed intopath()
as its first variable "invisibly"It is as if
os.path
is REALLY this:If there were a daisy chain I'd imagine that this:
Would be sort of like this in reality*:
Here comes the offensive part So with the self variable all that's doing is allowing the CLASS METHOD (from a rubyist perspective python 'instance methods' appear to be class methods...) to act as an instance method by getting an instance passed into it as its first variable (via the "sneaky" dot method above) which is called
self
by convention. Were self not an instancebut the class itself:
the class would get passed in rather than the instance.
OK, also important to remember is that the
__init__
method is called "magic" by some. So don't worry about what gets passed into generate a new instance. To be honest its probablynil
.I'll try to clear up some confusion about classes and objects for you first. Lets look at this block of code:
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 functioncreate_atm
. That's what the above code says.Now let's actually create a bank:
There,
x
is now a bank.x
has a propertycrisis
and a functioncreate_atm
. Callingx.create_atm();
in python is the same as callingBank.create_atm(x);
, so nowself
refers tox
. If you add another bank calledy
, callingy.create_atm()
will know to look aty
's value of crisis, notx
's since in that functionself
refers toy
.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:self
refers to the current instance ofBank
. When you create a newBank
, and callcreate_atm
on it,self
will be implicitly passed by python, and will refer to the bank you created.It may help you to think of the
obj.method(arg1, arg2)
invocation syntax as purely syntactic sugar for callingmethod(obj, arg1, arg2)
(except thatmethod
is looked up viaobj
's type, and isn't global).If you view it that way,
obj
is the first argument to the function, which traditionally is namedself
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.)