1
class MyController(BaseController):

    def index(self):
        # Return a rendered template
        #return render('/test.mako')
        # or, return a response
        return ''

Why does the function "index" have "self"?

I got this code from Pylons controller

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • 1
    Duplicate of all these: http://stackoverflow.com/search?q=python+self. Specifically http://stackoverflow.com/questions/2709821/python-self-explained – S.Lott Jun 02 '10 at 19:55

3 Answers3

3

Many languages, like C++ and Java, have an implicit pointer inside member functions. In those languages, it is "this". Python, on the other hand, requires an EXPLICIT name to be given to that pointer. By convention, it is "self", although you could actually put anything you like in there as long as it is a valid identifier.

Arcane
  • 1,230
  • 1
  • 8
  • 15
2

It's a member function (a function that's part of a class), so when it's called, the object it was called on is automatically passed as the first argument.

For example:

c = MyController()
c.index()

would call index with self equal to c. self is the standard name, but you can call it anything you want

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
  • Then can I use "self" inside the function "index"? print self.value – TIMEX Jun 02 '10 at 19:23
  • @alex Yes, if `MyController` has something named `value` (a field, function, etc.) – Michael Mrozek Jun 02 '10 at 19:23
  • If I declare a class, and then I put functions inside it, can I put "self" as an argument in every one of those functions? Is it recommended to have "self" as the first argument for all of them, followed by other arguments? – TIMEX Jun 02 '10 at 19:25
  • @alex If they're not static or class methods (by default they're not), Python will pass the instance as the first argument, so you need to have a variable there to receive it, you can't skip it. You should probably read the [Classes](http://docs.python.org/tutorial/classes.html) section of the Python tutorial – Michael Mrozek Jun 02 '10 at 19:30
1

Whenever a method in an object is called, the first parameter passed into that method is the object itself. If you do not define the first parameter as being the object you are using, you will get a TypeError exception.

Ishpeck
  • 2,001
  • 1
  • 19
  • 21