[Tutor] why must I explicitly use 'self'

D-Man dsh8290@rit.edu
Sun, 9 Jan 2000 20:02:45 -0500

On Wed, Jan 10, 2001 at 07:51:05AM -0500, Sharriff Aina wrote:
| Hi!
| Can someone explain exactly why I have to add "self" to a class function
| that I've defined?

Have you written any C++/Java/Eiffel code before?

In C++ you could write:

class blah
	void myfunction( void )
		cout << "Hello Class" << endl ;

You could also write:

class Foo
	string message = "Hello Class" ;

	void myfunction( void )
		cout << this->message << endl ;

They key point to note is the use of the keyword "this" in the second
example.  In C++/Java/Eiffel (Eiffel uses a different word, but I
can't remember it now) the 'this' keyword is automagically a pointer
to the current object.  In member functions, it is set automatically.
In freestanding functions (C++ only, the others don't allow it) the
'this' keyword isn't allowed.  

In Python, the "this" variable is passed to member functions as the
first argument to the function.  Thus every member function must take
at least one argument.  It is commonly called "self" in python, but
can actually be anything you like.  If you have a C++/Java background
you may want to use "this" instead.

# in Python:
class Foo:
	message = "Hello Class"

	def myfunction( self ) :
		print self.message


| Thanks for your anticipated help
| Sharriff

PS.  Replying to the digest isn't really a good idea -- the subject is
totatlly unrelated to your questions.  It is better to change the
subject to reflect your purpose in writing.