Newbie question: what's with "self"?

Simon Forman rogue_pedro at yahoo.com
Tue Aug 8 13:00:32 EDT 2006


donkeyboy wrote:
> This is probably a really basic question, but anyway ...
>
> I'm new to both Python and OO programming. From looking at a number of
> code examples, the word "self" is used a lot when referring to classes.
> As such, what does "self" mean and/or do? I've read things that say
> it's a naming convention, but no-one has really spelt it out (in idiot
> form!) in a way I can understand.
>
> Any help you can provide would be great: at the moment, when code
> doesn't work as expected, I'm randomly sprinkling "self"s in all over
> the place to see if that helps, but without much of an idea of what it
> really achieves.
>
> Thanks in advance!!

When you write a class, it works sort of like a template for creating
instances of that class.  The instances have variables (as attributes)
and use the methods (functions with the 'self' parameter) you define in
the class to manipulate the variables.

class foo:

    def __init__(self, value=0):
        self.value = value

    def get(self):
        return self.value

    def add(self, n):
        self.value += n

f = foo() # "magically" calls the __init__ method

# Call some methods on the instance.
print f.get()
f.add(23)
print f.get()

# Access the instance attribute directly.
print f.value
f.value -= 23
print f.value


# The above code prints:
0
23
23
0

Notice how, when you call f.get() and f.add(23), you don't pass in the
'self' parameter?  That's because when you call a method (get, add) on
an instance (f) of a class (foo), the python interpreter fills in the
'self' parameter for you as the instance itself.  (itSELF, get it?)

Put another way, inside the method, self == f.  If you were to create
another instance, g = foo(), and call the methods on/with it, g.get(),
then self == g.

Use can even use the class and pass in the instance yourself,
foo.get(f) and foo.add(f, 23), but there's almost never a reason to do
that.

I hope this helps.


(BTW, don't randomly sprinkle things in your code.  Programming ain't
like cooking.  You can't just add a dash of 'self's and a sprinkle of
'if..then..'s.  :-)  You should know what you are doing and why.  If
not, read and ask questions.  Computers are deterministic machines that
do exactly what you tell them to.  If you tell them to do random things
you'll get random results, and if *you* don't even understand your code
then it's quite likely no one will and all you'll have is pointless
junk.  (And if there's one thing  I've learned reading and posting to
c.l.p in the last couple of months, it's that there's *plenty* of
pointless junk around already.)  One exception to "don't sprinkle
things" would be print statements, but even there, don't sprinkle
randomly...) :-)

Peace,
~Simon




More information about the Python-list mailing list