Newbie question: what's with "self"?

skip at pobox.com skip at pobox.com
Tue Aug 8 14:07:05 EDT 2006


    donkeyboy> This is probably a really basic question, but anyway ...  I'm
    donkeyboy> new to both Python and OO programming. From looking at a
    donkeyboy> number of code examples, the word "self" is used a lot when
    donkeyboy> referring to classes.  As such, what does "self" mean and/or
    donkeyboy> do? 

"self" is a name refering to the particular instance whose method is being
called.  If I have

    class C:
        def __init__(self):
            self.x = 7

        def printx(self):
            print self.x

    a = C()
    b = C()

If I call a.printx(), self will be bound to the same object a is bound to.
If I call b.printx(), it will be bound to the object b references.

The precise use of the name "self" is indeed simply a convention.  You could
call it "barney" if that makes you feel better. ;-)

Skip



More information about the Python-list mailing list