[Tutor] **kw and self

alan.gauld@bt.com alan.gauld@bt.com
Thu, 21 Jun 2001 13:06:04 +0100


> Java and the like don't have self as an implied argument.

Actually they do.
In C++ and Java its called 'this'
In Delphi and Smallktalk (and objective C???) its called 'self'

The difference is it is implied and you don't need to declare it:
In C++:

class C
{
private:
   int aValue;
public:
   C(int n){aValue = n) 	// no 'this' here
   void foo(){ 			// no mention of 'this' here either
      cout << this->aValue;   // so where'd it come from?
   }
}

C *c;
c = new C(7);
c->foo();

The 'this' reference in foo() just appeared by magic 
because its implied in the language. When you create an 
instance and use it C++(and Java) automatically creates 
a this variable that points to the particular object.

You don't often need to use 'this' in C++ or Java, (altho' 
many professionals do so to distinguish class attributes 
from local variables) but python chooses to make it explicit 
so its harder to make a mistake. After a while you get to 
prefer it that way(at least I do :-)

HTH,

Alan G.