this or self - what are they, and what is the difference? (Python)
Archive - Originally posted on "The Horse's Mouth" - 2012-12-08 13:04:46 - Graham EllisIn any object oriented language, you'll have a number of different objects of the same type, and you'll need to be able to refer to a paricular attribute within a particular object - usually, you'll call a named piece of code (a method) on an object and need to say "on THIS object" ... let me rephrase that in an example ...
I have two tables in my restaurant. One is made of glass and the other is made of pine. And I run a piece of code asking what material is THIS table made of. Depending on which table object I run my method on, the answer could be "this table is made of glass" or "this table is made of pine".
In Python, the first parameter to a normal (or dynamic or object) method in a class is the reference to the current object. In many of my demonstrations to newcomers, you'll find me using the name current for the variable, but it's most common to use self. And there's no reason at all why you can't use the variable name this. None of these are reserved words, and you can even vary the word you use from one method to the next. Code-wise, it's no more that a place holder; some tools may prefer you to use one word or another, though.
Example code - [here] - which used self, this and current, and a data file that goes with the example is [here]. The example also shows the use of a factory pattern (again, factory is just a name and we have actually called our method make)
Note - in some languages such as Java and PHP, the "current object" word is a reserved name rather than being declared at the top of the method, and you can't choose to change it from this.