[Tutor] Hello and newbie question about "self"

Alan Gauld alan.gauld at btinternet.com
Mon Feb 4 00:50:49 CET 2008

"Patrick" <python-list at puzzled.xs4all.nl> wrote 

> Can anyone please point me to a document that explains "self" in
> layman's terms. 

Try the OOP topic inmy tutorial...

> Or lacking such a doc throw in a much appreciated
> layman's explanation what "self" is and when/where to use it? 

Others have given code samples but a conceptuial explanation 
is that 
a) self is only used in OO programming within metjhods of a class.
b) self refers to the actual instance of the object receiving the 
    message with caused the method to be invoked.

Thus if we have a class C with a method m and 3 instances 
a,b and z then when we invoke a.m() self will refer to a and 
when we invoke b.m() self will refer to b. This means that the 
innards of the method can use self to access the instance 
specific data for that invocation.

If you have used C++ at all you might recognise it as the 
same as 'this' in C++ except that in Python you must explicitly 
specify it whereas C++ creates 'this' magically behind the scenes.

See my tutorial for more on this under the heading 
"Using classes".

If you haven't started writing classes yet, you can safely ignore 
it for now!

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list