[Tutor] Hello and newbie question about "self"
Michael Langford
mlangford.cs03 at gtalumni.org
Sun Feb 3 22:15:45 CET 2008
In C, you may have "objectorientedesque" code like the following;
struct net {
int foo;
int bar;
int baz;
};
void populate_net( struct net* mynet, int fooval, int barval)
{
mynet->foo = fooval;
mynet->bar = barval;
mynet ->baz = fooval * 5;
}
int connect_to_net(struct net* mynet)
{
return open_internet_connection(mynet->foo);
}
int main (void)
{
struct net inet;
populate_net(&inet,2,2);
int returncode = connect_to_net(&inet);
printf("%d\n",returncode);
}
In that batch of C code, you manipulate the struct without fiddling
with its fields in the user code. You let the functions change its
values so that they are done correctly.
In python, you are doing something similar. However, they make some
syntactic sugar to make it so you don't have to pass the object in
explicily. That is what self is.
So the analgous python code is:
class net(object):
def __init__(self,fooval,barbal):
self.foo = fooval
self.bar = barval
self.baz = fooval*5
def connect_to(self):
return open_internet_connection(self.foo)
inet = net(2,2)
returncode = inet.connect_to()
print returncode
See how you don't have to pass in the inet object in? Instead you call
it with the inet.connect_to() function, and the object itself is
passed in explicitly as self?
That's all it is.
Btw, make sure to always include "self". Otherwise you'll be writing a
class method and it doesn't work the same way.
--Michael
On Feb 3, 2008 3:15 PM, Patrick <python-list at puzzled.xs4all.nl> wrote:
> Hi guru's,
>
> New to the list. I bought O'Reilly's Learning Python (3rd edition for
> 2.5) a while back. Slowly making my way through it and was pleasantly
> surprised that Python seems easier than C. Until...I bumped into the
> "self" thingy.
>
> Can anyone please point me to a document that explains "self" in
> layman's terms. Or lacking such a doc throw in a much appreciated
> layman's explanation what "self" is and when/where to use it?
>
> In the book (so far) I've seen "self" pop up in these examples (on pages
> 457 and 458):
>
> class C1(C2, C3):
> def setname(self, who)
> self.name = who
>
> class C1(C2, C3):
> def __init__(self, who)
> self.name = who
>
> Thanks for any pointers!
>
> Regards,
> Patrick
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--
Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com
More information about the Tutor
mailing list