Newbie question: what's with "self"?

Thomas Bartkus thomasbartkus at comcast.net
Tue Aug 8 13:09:50 EDT 2006


"donkeyboy" <fivenastydisco at hotmail.com> wrote in message
news:1155054411.511813.203270 at i42g2000cwa.googlegroups.com...
> 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!!
>

To put it simply, a class needs a way to know which instance (of itself!) to
operate on.

If you have a class "str" (and Python has that built in!), then there will
be many instances of class "str" in a typical program.  The parameter "self"
refers to the particular string the class method is being called to operate
upon.

If you have a method upper() that convert everything to uppercase, your
class definition would need the "self" parameter in order to know which
particular string to convert.

Thomas Bartkus





More information about the Python-list mailing list