[Tutor] Hello and newbie question about "self"
Patrick
python-list at puzzled.xs4all.nl
Mon Feb 4 01:34:05 CET 2008
Hi Michael,
Michael Langford wrote:
> 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);
> }
Heh I had to grab my C book and browse up on structs and pointers to get
an idea what this was all about :)
> 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.
Ok that makes sense.
> 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.
Got it.
> 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?
Aaah starting to understand now.
> 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.
Thanks for the elaborate explanation!
Regards,
Patrick
More information about the Tutor
mailing list