Newbie question: what's with "self"?

Bruno Desthuilliers onurb at xiludom.gro
Tue Aug 8 14:26:23 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.

Actually, it's used as the first parameter for methods of the classes -
but, due to Python's magic, doesn't need to be passed when calling the
method on an instance.

> As such, what does "self" mean and/or do? 

It's a reference to the class's instance on which the method was called,
- and it's necessary to have it to know on which instance the method
should act.

> I've read things that say
> it's a naming convention,

The name 'self' is a convention, yes - you could name it "shruberry" or
"parrot" as well, but it would be rather unusual and somewhat confusing.
FWIW, Python relies a *lot* on naming conventions, and it's better to
stick to them.

>  but no-one has really spelt it out (in idiot
> form!)

Since you ask for it:

<idiot-form>

def reallyspellout(word):
  for letter in word:
    print "'%s'" % letter,

it = 'self'
reallyspellout(it)

</idiot-form>

Was this idiot enough ?-)


> in a way I can understand.

oops, sorry :(

Well, cf above and other answers in this thread then.

> 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. 

This is known as "accidental programming". A total waste of time and
effort. Read the doc, use google, try to understand, test, and when
something don't work out as expected, ask here. Don't forget the first
three steps.

HTH



More information about the Python-list mailing list