-5

Possible Duplicate:
Python ‘self’ explained

I have looked for some time but i still don't understand self in python

def cut(self, cats, dogs):
     self.cats = cats
     self.dogs = dogs
     print cats, dogs
cut(1,5)
Community
  • 1
  • 1
  • What don't you understand about it? What it's used for? Why it's used? – Blender Oct 27 '12 at 00:31
  • http://stackoverflow.com/questions/2709821/python-self-explained – John Oct 27 '12 at 00:31
  • There's [this SO answer](http://stackoverflow.com/q/2709821/1079354) and [this page from the docs](http://docs.python.org/tutorial/classes.html#random-remarks). You could call `self` `this`, if it helps you understand it a bit better (it's pretty similar). – Makoto Oct 27 '12 at 00:32
  • 6
    @Makoto: ...but don't, since that will reduce the readability of your code (to other Python users, at least). – nneonneo Oct 27 '12 at 00:33
  • Of course not. That's exactly what the docs say! :P – Makoto Oct 27 '12 at 00:42
  • You get down votes for asking a question you don't know the answer to. Don't do it! – zortacon Oct 27 '12 at 00:46

1 Answers1

4

self is just a local variable. You could name it anything you like, but the convention is to name it self. When a function is invoked as a method, i.e. on an actual object, Python will pass a reference to the object as the first argument. This is what self points to.

obj.method(param) is actually just syntactic sugar for ObjType.method(obj, param). So that's where the parameter comes from.

poke
  • 369,085
  • 72
  • 557
  • 602