Is it advisable to replace 'self' with '_' or 'I' or something shorter?

oofoe joshfuller at operamail.com
Tue Jan 21 15:13:34 EST 2003


Hi!

jbperez808 at yahoo.com (Jonathan P.) wrote in message news:<f57664b9.0301110959.5b1439da at posting.google.com>...
> I agree with the fact that explicit use of self is good
> for code readability, however it tends to make code lines
> too long.  Since 'self' is just a convention, I wonder if
> people out there have tried replacing it with a one-character
> equivalent without encountering any problems.

I dislike the word 'self' for the method's object argument. It's
clumsy to say and lends an unwarranted arrogance and formality
to the method call. I prefer the much more friendly name 'my'.
It's one letter longer than your preferred length, but it's
very natural. To paraphrase Mark Twain, it's a name that's willing
to roll up its sleeves, spit on its hands and get right to work,
instead of setting out for a scenic sail across a vast ocean of
verbose bureaucratese. See for yourself:

class uptight:
   name_christian = "Victor"
   name_family = "Blendeloquene II"
   age_in_years = 56

   def describe(self): 
      print "%s %s is %s years old." % (
         self.name_christian, 
         self.name_family, 
         self.age_in_years)

class cool:
   name = "Jack Flash"
   nick = "Jumpin'"
   sign = "aquarius"

   def hi(my): print "I'm " + my.name + ", call me " + my.nick + "."

   def baby(my): my.hi(); print "I'm an " + my.sign + ", how about you?"

a = uptight(); a.describe(); print

k = cool(); k.baby()

As you can see from the code samples above, the second class (the 
'cool' one) is much easier to read and far more compact than the
'correct', but thoroughly uptight, version at the top. Notice also
the expressiveness of the code. The cool class has already got
the next dance lined up in eight lines of code before the uptight
class has managed to finish introducing himself in ten.

A key point is that the 'my' name connotes possessiveness in the
created clause, whereas the 'self' name can only form a clumsy
compound name: "my.name" as opposed to "self.name". 

The one possible fly in the ointment is that many writers of 
introductory computer programming texts like to use 'my' as a prefix
to a user written function, such as 'myPrint()' or 'myOpen()' or
even 'myHeadIsFilledWithAir()'. Since no working programmer follows
this practice for longer than ten minutes after finishing CSCI101, I
propose that the textbook authors use the 'self' as a prefix instead,
clearing the way for 'my' to enter the common lexicon.

I'm only half joking.

Jos'h




More information about the Python-list mailing list