views:

722

answers:

5

Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP.

I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self" : the program will work fine.

So where does this convention come from ?

+14  A: 

Smalltalk, which predates Java of course.

tragomaskhalos
Thanks pale, will sleep better tonight.
e-satis
+15  A: 

Check the history of Python for user defined classes:

Instead, one simply defines a function whose first argument corresponds to the instance, which by convention is named "self." For example:

def spam(self,y):
    print self.x, y

This approach resembles something I had seen in Modula-3, which had already provided me with the syntax for import and exception handling.

It's a choice as good as any other. You might ask why C++, Java, and C# chose "this" just as easily.

duffymo
Sorry mate, but really you are just repeating what I said in the question : python uses self, it's a convention. The question is why.
e-satis
The quotes and link explain the creator of Python's motivation. It would be difficult to get a better 'why' than that. Duffymo isn't repeating your question - Guido is.
Joel Hooks
"...something I had seen in Modula-3..." - it's got more documentation than "Smalltalk because I said so." I believe the "I" in the history is BDFL Guido.
duffymo
Didn't follow the link. My mistake.
e-satis
+30  A: 

Smalltalk-80, released by Xerox in 1980, used self (1980). Objective-C (early 1980s) layers Smalltalk features over C, so it uses self too. Modula-3 (1988) and Python (late 1980s) follow this tradition.

C++, also dating from the early 1980s, chose this instead of self. Since Java was designed to be familiar to C/C++ developers, it uses this too.

Jim Ferrans
Object Pascal (both the early Apple and the later Borland flavours, including Delphi) also went with "self".
Paul-Jan
Smalltalk and Objective-C both use the metaphor of objects sending messages to each other, so "self" just indicates that the object is sending a message to itself. (It's always seemed more natural to me to use "self" instead of "this".)
Jim Ferrans
Not to forget self, the language :)
Adrian
+3  A: 

I think that since it's explicity declared it makes more sense seeing an actual argument called "self" rather than "this". From the grammatical point of view at last, "self" is not as context dependant as "this".

I don't know if I made myself clear enough, but anyway this is just a subjective appreciation.

fortran
+4  A: 

The primary inspiration was Modula-3, which Guido was introduced to at DEC:

the Modula-3 final report was being written there at about the same time. What I learned there showed up in Python's exception handling, modules, and the fact that methods explicitly contain “self” in their parameter list.

-- Guido, Linux Journal Interviews Guido van Rossum

cdleary