Search code examples
pythonself

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


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)

Solution

  • 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.