[Tutor] Classes and "Self"

Benoit Dupire bdupire@seatech.fau.edu
Fri, 27 Apr 2001 11:05:35 -0400


Here's my try: ;o) Correct me if i am wrong

>>> class Foo:
    def __init__(self, value):
        i = 8
        self.name = value


>>> dir(Foo)
['__doc__', '__init__', '__module__']
>>> a=Foo(12)
>>> dir(a)
['name']


Why self ?
Namespace issue!
>From within __init__, the local namespace consists of all the variables defined
within __init__ (ie i can access 'i')
The global namespace is the module (ie. i can access a).
and there is the built in namespace....

I can't access 'name' directly from __init__ because it is in the object
namespace (somewhat nested), and thus it's not local to __init__ or global to
the module
I can access 'name' from the global namespace, using 'a.name'.
So i can access 'name' from __init__ only if i have got a reference to 'a', so
that i can use 'a.name'

As the problem occurs for every instance variables, we need this ref every time
and to pass it, and the convention is to call it self.
When you call __init__(a, 12)  then you create 2 variable in the __init__
namespace  self, and i.






"Mark A. Tobin" wrote:

> Hi there,
> I've been playing around with Python for a while now as my first real foray
> into programming.  I've just started looking at creating classes as they
> seem to be the more "mature" way to structure one's programming.  I can now
> implement instances and what not, thanks to some of the great tutorials out
> there, however I can't figure out what the "self" argument is all about.  It
> is used throughout the program to refer to something, but I don't really
> "get it".  As I said, I can use it (i.e.. repeat the structure I've seen in
> the tutorials by rote), but I don't really know why or how I'm using it.
> An explanation or a point to an explanation would be helpful,
>
> Mark
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

--
Benoit Dupire
Graduate Student
----------------
I'd like to buy a new Boomerang. How can i get rid of the old one?