views:

94

answers:

3
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

+2  A: 

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
Then can I use "self" inside the function "index"? print self.value
TIMEX
@alex Yes, if `MyController` has something named `value` (a field, function, etc.)
Michael Mrozek
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
@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
+3  A: 

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  A: 

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