What is self?

Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called method will think it is called as meth(x, a, b, c).

See also Why must ‘self’ be used explicitly in method definitions and calls?

CATEGORY: programming

 

Comment:

While I know that "self" is stated to be a convention, I bet that many new PyProgrammers will read right past that. Perhaps an example will make it clear that you *can* use self, my, this, i.e. baseclass.methodname(self, <argument list>) == baseclass.methodname(this, <argument list>) ... but state that common practice is that most all of us use self, and its jarring to many when some other name is used. ??? Use or discard as you like.

Posted by Michael Watkins (2006-11-13)

Comment:

Because the methods of an object are defined in the class definition, when a method is called it needs a reference to the specific instance of the class on which the method was called. Suppose you defined a method as class MyClass: def mymethod(self, arg1, arg2): ... If you have an instance x of MyClass and you write a call like x.mymethod(1, 2) the interpreter effectively changes this to MyClass.mymethod(x, 1, 2) In other words, the self argument receives the instance on which the method is being called.

Posted by Steve Holden (2006-11-16)

Comment:

As i have understood it, self is used when you want to use variables that you can reference and modify. The variabels assigned with self are visible after you have created an instance of the class. If you dont assign variables with self they will just disappear.

Posted by Akin (2007-04-28)

A Django site. this page was rendered by a django application in 0.03s 2008-09-08 17:53:11.052503. hosted by webfaction.