[Zope] self()....what is it?

Paul Winkler slinkp23@yahoo.com
Wed, 7 Nov 2001 12:16:23 -0500


On Wed, Nov 07, 2001 at 01:49:11PM +0000, Aruna Prabhakaran wrote:
> hi,
> I am just not able to get the concept of the "self" in python.I came across 
> the source code for the pop method of a stack on the python website.but it's 
> just passing over and above my head:(((Can somebody explain to me why and 
> how it is used?(reminds me of the 'void' of good old C:)

I assume you have at least some very basic understanding of object
oriented programming? i.e. you know what is meant by terms such as
"class" and "method"?

Think of it this way: When you write a class, you need a way to refer
to methods and data that live in *the current instance of the
class*. How can you do that when you can't possibly know ahead of time
what name might be given to a particular instance of the class?

In C++, this problem is solved with a keyword, "this" (which often is
implicit).  In Python, there's no keyword. Instead, the *first
argument* to a class method is taken as "the current object". It
doesn't actually matter what you call it, but "self" is used almost
universally by python programmers.

Example:

class Spam:

    def set_food(self, something):
        self.food = something
        # sets an attribute of the instance 

    def get_food(self):
        print self.food

a = Spam()          # create an instance of the class
a.set_food('eggs')
a.get_food()        # prints 'eggs'
print a.food        # same thing!

Notice that when we call these methods, we don't explicitly pass in
the value to use for "self". Python takes care of that for us.  So
when you call a method, you use one less argument than you defined it
with.

I hope that was more helpful than confusing.

> Also looks like self is being treated as list/tuple here why?
> -----------------------------------------------------
> def pop(self):
> 	if len(self):
> 	    res =  self[-1]
> 	    del self[-1]
> 	    return res
> 	else:
> 	    raise IndexError, "Stack %s is empty"%self.name()

Well, I haven't seen the class this code comes from, but apparently it
implements some list behavior. This is pretty easy to do - you can
subclass from UserList and/or define a number of special methods that are
used behind the scenes by built-in functions (like len) and by list
notation (the square brackets). 

This stuff is documented in the python Reference Manual, section 3:
http://www.python.org/doc/current/ref/specialnames.html

Incidentally, python's list type has had a pop method for quite a
while...  that example is either old or contrived.

-- 

paul winkler
home:  http://www.slinkp.com
music: http://www.reacharms.com
calendars: http://www.calendargalaxy.com