1

I can understand why it is needed for local variables, (self.x), but why is is nessecary as parameter in a function? Is there something else you could put there instead of self?

Please explain in as much layman terms as possible, I never had decent programming education.

user3500869
  • 172
  • 1
  • 7
  • 2
    The name `self` is the convention; but you can flaunt the convention and use a different name if you really wanted to. – Martijn Pieters Apr 08 '14 at 14:04
  • 1
    Have a look at http://stackoverflow.com/questions/2709821/python-self-explained – fredtantini Apr 08 '14 at 14:05
  • 2
    There are a long list of possible duplicates here: [Python 'self' explained](http://stackoverflow.com/q/2709821), [How to avoid explicit 'self'?](http://stackoverflow.com/q/1984104), [python and using 'self' in methods](http://stackoverflow.com/q/3283178) and [Explaining the python 'self' variable to a beginner](http://stackoverflow.com/q/6990099) – Martijn Pieters Apr 08 '14 at 14:07
  • `self` refers to object itself . – Nishant Nawarkhede Apr 08 '14 at 14:11

4 Answers4

4

If you consider it, EVERY programming language does that - or, at least, the most common languages like pascal, c++ or java do). EXCEPT that, in most programming languages, the this keyword is assumed and not passed as a parameter. Consider the function pointers in those languages: they're different than method-pointers.

Pascal:

function(a: Integer): Integer;

vs

function(a: Integer): Integer of object;

The latter considers the self pointer (yes, it's named self but it's an implicit pointer like the this in c++, while the python self is explicit).

C++:

typedef int (*mytype)(int a);

vs

typedef int Anyclass::(*mytype)(int a);

As difference with Pascal, in C++ you must specify the class owning the method. Anyway, this method pointer declaration states the difference between a function expecting a this or not.

But Python takes seriously it's Zen, as quichua people takes seriously their Ama Suway, Ama Llullay, Ama K'ellay:

Explicit is better than implicit.

So, that's why you see explicitly the self parameter (and must write it, of course) for instance methods and @classmethods (althought it's usually called cls there since it's intention is to dynamically know the class and not the instance). Python does not assume a this or self keyword must exist inside the methods (so, the namespace has only true variables - remember you are NOT forced to name them self or cls althought it's usual and expected).

Finally, if you get:

x = AClass.amethod #unbound method

You must call it as

x(aninstance, param, param2, ..., named=param, named2=param2, ...)

While getting it as:

x = anInstance.method #bound method, has `im_self` attribute set to the instance.  

must be called as:

x(param, param2, ..., named=param, named2=param2, ...)

Yes, the self is explicit in the parameter list since it's not assumed a keyword or 'backdoor' must exist, but not in the argument list because of syntactic sugar every OOP language has (weird criteria, huh?).

Luis Masuelli
  • 12,079
  • 10
  • 49
  • 87
4

By default, every function declared in the namespace of a class assumes that its first argument will be a reference to an instance of that class. (Other types of functions are decorated with @classmethod and @staticmethod to change this assumption.) Such functions are called methods. By convention, Python programmers name that first parameter self, but Python doesn't care what you call it. When a method is called, you must provide that reference. For example (with self replaced by foobar to demonstrate that self is not the required name):

class A:
    def __init__(foobar):
        foobar.x = 5

    def somefunc(foobar, y):
        print foobar.x + y

a = A()
print A.somefunc(a, 3)   # Prints 8

Python provides some syntactic sugar to make the link between an object and a method called on it more obvious, by letting you call a bound method instead of the function itself. That is, a.somefunc(3) and A.somefunc(a, 3) are equivalent. In Python terminology, A.somefunc is an unbound method, since it still needs an instance when it is called:

f = A.somefunc
print f(a, 3)

By contrast, a.somefunc is called a bound method, since you have already provided the instance to use as the first argument:

f = a.somefunc
print f(3)
chepner
  • 497,756
  • 71
  • 530
  • 681
1

It's how Python's implementation of object oriented programming works -- a method of an instance (a so-called bound method) is called with that instance as its first argument.

Besides variables of the instance (self.x) you can also use it for anything else, e.g. call another method (self.another_method()), pass this instance as a parameter to something else entirely (mod.some_function(3, self)), or use it to call this method in the superclass of this class (return super(ThisClass, self).this_method()).

You can give it an entirely different name as well. Using pony instead of self will work just as well. But you shouldn't, for obvious reasons.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
1

The use of self for the first reference in a method is entirely convention.

You can call it something else, even inconsistently in the same class:

class Foo(object):
    def __init__(notself, i):
        notself.i=i             # note 'notself' instead of 'self'

    def __str__(self):
        return str(self.i)      # back to the convention   

f=Foo(22)

print f

But please don't do that. It is confusing to others that may read your code (or yourself when you read it later).

dawg
  • 98,345
  • 23
  • 131
  • 206