What is "self"?

James Stroud jstroud at mbi.ucla.edu
Thu Sep 22 22:43:05 EDT 2005


I'm sure there are answers to this out there, but I'm typing this one up so I 
can show it to people that I try to teach this language. They consistently 
get hung up on what self is. So here is my try:

==

Self is one of those python concepts that new python programmers have a little 
difficulty with. It refers to the instance of the class that is calling the 
method. That's confusing, so let's do an example.

Say you have a class called Thing

    class Thing:
      def __init__(self, aval):
        self.value = aval
      def doit(self, another_val):
        print "Time 'till end of world:", (self.value + another_val)


You can instatiate the thing class

    athing = Thing(1)

The object referenced by the name "athing" lives in your computers memory 
somewhere. The name "athing" is how we reference, or talk about, that object. 
Above, "doit" is a member function of the Thing class. How can we call doit?

    athing.doit(5)

What happened here? Why did we need self in the definition of doit when we 
didn't obviously pass something that we could construe as self? Well, we did 
pass something we could construe as self, it was "athing". How is this? Well,

    athing.doit(5)

is equivalent to (and shorthand for)

    Thing.doit(athing, 5)

Here is a picture of what this did:

    def doit(self, another_val)
              ^          ^
            athing       5

       print "Time 'till end of world:", (self.value + another_val)
                                              ^             ^
                                          athing.value      5


This complies with the signature of the "Thing.doit" member function. The 
compiler turned the shorthand "athing.doit(5)" into "Thing.doit(athing, 5)" 
for us, saving us a little typing in the process and making our code easier 
to read.

So, when we talk use self as a name in class member functions, we are actually 
referencing the instance that was passed to the member function. So for this 
example "athing" and "self" reference the same object. If an instance called 
another_thing was passed, then another_thing and self would refence the same 
object:

    another_thing = Thing()
    Thing.doit(another_thing, 5)  # same as another_thing.doit(5)

==

On Thursday 22 September 2005 18:36, Wayne Sutton wrote:
> OK, I'm a newbie...
> I'm trying to learn Python & have had fun with it so far.  But I'm having
> trouble following the many code examples with the object "self."  Can
> someone explain this usage in plain english?
>
> Thanks,
> Wayne

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list