tags:

views:

152

answers:

6

From what I read/understand, the 'self' parameter is similiar to 'this'.

Is that true?

If its optional, what would you do if self wasnt' passed into the method?

+1  A: 

In classes a self variable (or cls for classmethods) is required. What you want to call it is your decision though. If you prefer you could call it this instead.

A classmethod is a method that gets the class as a first argument instead of a instance. It can be called without passing an instance. i.e. with a classmethod you can do:

SomeObject.some_class_method()

while a normal method would require you to do

SomeObject().some_normal_method()
or
SomeObject.some_normal_method(instance)
WoLpH
cls is for 'class methods', meaning static methods correct?
Blankman
No, in Python [static methods](http://docs.python.org/library/functions.html#staticmethod) are different.
Matthew Flaschen
@Matthew Flaschen is correct. A class method receives a reference to the class as its first parameter, a static method has no required parameters.
danben
+5  A: 

Yes, it's used in similar ways. Note that it's a positional parameter and you can call it what you want; however there is a strong convention to call it self (not this or anything else). Some positional parameter must be there for a usable instance method; it is not optional.

Matthew Flaschen
"It must be there" might suggest to the uninitiated that _It_ is `self`. I'd like to clarify that, the first parameter must be there and will point to an instance of the object. It is called `self` by convention but if you write code for an obfuscated coding contest you _could_ call it something different.
extraneon
@extra, I've clarified.
Matthew Flaschen
+1  A: 

self is this, just you have to explicitly pass it and explicitly use it to refer to class methods/properties.

It isn't optional in class methods. You will get a TypeError if you try to define a classmethod without at least one argument (i.e., the self parameter).

However, you can call it something other than self, but I have never seen otherwise.

orangeoctopus
You should rephrase. [`classmethod`](http://docs.python.org/library/functions.html#classmethod) is something different.
Matthew Flaschen
A: 

self refers to the object on which the method was called, much like this in C++. But it is important that self is merely a convention, you can name it as you like and pass instances of subclasses.

Philipp
+1  A: 

The joy of Python

That is true to some extend. Methods are bound to the object instance they are a part of. When you see

def some_func(self, foo, bar)

The passing of self is sometimes implicit when you call, for example:

obj.some_func(foo_val, bar_val)

Which is equal (presuming obj is of class MyClass) to

MyClass.some_func(obj, foo_val, bar_val)

Because the method is bound to obj, the self argument gets populated. This is part of Python being explicit with what it means. In other languages, this just pops into scope, with Python there is some exposure of how this happens.

You can also pass methods around, and manually pass them self when not calling from a bound context.

The Python docs do a good Job:

xf = x.f
while True:
   print xf()

will continue to print hello world until the end of time.

What exactly happens when a method is called? You may have noticed that x.f() was called >without an argument above, even though the function definition for f() specified an >argument. What happened to the argument? Surely Python raises an exception when a function >that requires an argument is called without any — even if the argument isn’t actually >used...

Actually, you may have guessed the answer: the special thing about methods is that the >object is passed as the first argument of the function. In our example, the call x.f() is >exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments >is equivalent to calling the corresponding function with an argument list that is created >by inserting the method’s object before the first argument.

Aiden Bell
A: 

self is definitely similar to this, however, in Python, the name self is just a convention, and could be named anything else. The variable is named after whatever you call it in the function's prototype (def function(whatever, params...):).

For instance methods, self IS actually required. For class or static methods, you need to specify that they should be treated as such, and then self is not required. For example:

def type_to_display(type):
    """Converts a pass type to the full written pass type."""
    return list((pair[1] for pair in Pass.TYPE_CHOICES if pair[0] ==      
                          type[0:1].upper()))[0]                          
type_to_display = staticmethod(type_to_display)      

You will never be able to use an instance method in such a way that self is not passed in. For example, if I have an instance my_car of a Car class, and I use the Car class's drive instance method, the my_car instance will be implicitly passed into the drive method as the first parameter (self).

class Car:
    def drive(self):
        self.do_some_stuff()

my_car = Car()
my_car.drive() # actually calls Car.drive(my_car)
Alan Christopher Thomas
it calls Car.drive(my_car)
Aiden Bell
Bah, thanks! Fixed.
Alan Christopher Thomas