[Tutor] Classes and "Self"

VanL vlindberg@verio.net
Fri, 27 Apr 2001 13:32:31 -0600


I'll try too.  This may be a bit long-winded, but I'll get to your
question.  

The concept  of object-oriented programming (OOP) was invented, in part,
to help make software contructs that mirrored their real-world
counterparts.  Previous imperative programs worked more like a recipe --
take the ingredients, follow a procedure, produce an output.  While this
worked well for a lot of problems, there were certain problems that
didn't match well to this style of solving a problem.

Take, for instance, a software model that would drive a (virtual) car. 
In an imperative program, the program would need to know a lot about how
all of the different parts of the car worked -- after all, the same
'recipe' would control everything from steering to the drivetrain to the
electrical system.

In an important sense, though, that isn't how we drive a car.  We don't
have to worry about the drivetrain or the electrical system while we are
steering -- we have a couple of well-defined controls (the steering
wheel, pedals, etc) to tell the car what we want to do and we don't
worry about the underlying mechanics of how it all works.

Thus, this problem could be modeled more closely by imagining a set of
interacting players, each of which did one particular thing.  The
'driver' object steered, the 'drivetrain' object transmitted power,
etc.  These objects worked with each other via defined interfaces. 
Furthermore, an interacting collection of objects could itself be
considered an object, just like we take a bunch of parts, put them
together, and call them a car.  

Now when we think of a physical object with controls, it is sort of hard
to imagine the steering wheel of one car actually controlling some other
car down the street.  With software, though, it was possible to do just
that.  Hence, it was necessary to define which object went with which
set of controls.

Now when you declare an instance of an class, you are actually doing two
things: 1. creating the instance (the object) and 2. naming it
uniquely.  This enables the computer to keep track of which set of
controls goes with each object.  The 'self' parameter is the object's
internal name -- it lets the computer know which object you actually
want to do stuff with.

HTH,

VanL