[Tutor] What is self?
Alan Gauld
alan.gauld at blueyonder.co.uk
Thu Aug 19 10:14:04 CEST 2004
> I notice this in a lot of python programs:
> def name(self):
> self.something = None
>
> what does the self mean?
It is shorthand for a reference to the current object.
The functions you see written that way are embedded inside classes.
When you create an instance of the class the instance has a
copy of the data but not the metods. Thus when we send a message
to an instance and it calls the corresponding method, it does
so via a reference to the class. It passes a reference to itself
(self!) to the method so that the class code knows which instance
to use.
Thus the client code calls the instance.
The instance calls the class method, passing a reference to itself
The class method then uses the reference to pick up the instance
data (the self.something bits)
You can see this in action by explicitly calling the class method:
>>> class C:
... def __int__(self, val): self.val = val
... def f(self): print "hello, my value is:", self.val
...
>>> a = C(27)
>>> b = C(42)
>>> # first try sending messages to the instances
>>> a.f()
hello, my value is 27
>>> b.f()
hello, my value is 42
>>> # now call the method explicitly
>>> C.f(a)
hello, my value is 27
I hope that clarifies? If you haven't done OOP yet, don't
get too hung up on it. When you do use OOP you still don't
need to worry, just follow convention and it will just work!
And this reminds me that I intended putting a deeper
explanation of self in my rewritten tutor but haven't
yet. So another addendum coming up...
Thanks for reminding me! :-)
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/
More information about the Tutor
mailing list