The need to put "self" in every method

Terry Hancock hancock at anansispaceworks.com
Wed Jun 1 15:28:56 EDT 2005


On Tuesday 31 May 2005 11:52 am, Roy Smith wrote:
> Note that in languages like C++ where using "this->" is optional,
> people invent their own conventions for keeping local and instance
> variables distinct, like prepending m_ to member names (except that
> different people do it different ways, so it's more confusing).

I would call this the "real" answer.  I am aesthetically annoyed by
code like:

Post.postRead()

or even

Post.read_post()

The dot is there for a reason -- it qualifies the variable with the
class it applies to.  What is the point of qualifying it AGAIN in the
method name?   When I notice this in my own code, I reduce such
stuff to

Post.read()

IMHO, redundancy interferes with clarity, and one should use
the semantics of the language to describe the semantics of the
program --- that should make it easier for both Humans and
machines to understand the relationships in the code.

Using "self" is just like this, as indicated above: it replaces weird
naming conventions with a much more general one. 

I've only ever replaced "self" with a different name once, and
that was when I was writing a vector math module -- I wanted
a more compact symbolic style, so I used "a":

def __add__(a,b):
    return Vector((a.x+b.x), (a.y+b.y), (a.z+b.z))

or something like that.  I still have twinges of guilt about it,
though, and I had to write a long note in the comments, apologizing
and rationalizing a lot. ;-)

I must say though, that as a newbie, I found this a lot easier
to get my head around than learning all the implicit variables
that Javascript introduces (e.g. "this", "prototype", etc).

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list