Many of them are asking a language-design question: Why does Python require explicit self when other languages like C++ and friends (including Java), JavaScript, etc. do not? Guido has answered that question many times, most recently in Why explicit self has to stay.
But some people are asking a more practical question: Coming from a different language (usually Java), they don't know how to use self properly. Unfortunately, most of those questions end up getting interpreted as the language-design question because the poster is either a StackOverflow novice who never figures out how to answer comments on his question (or just never comes back to look for them) or a programming novice who never figures out how to ask his question.
So I'll answer it here.
tl;dr
The short version is very simple, so let's start with that:- When defining a method, always include an extra first parameter, "self".
- Yes, that's different from Java, C++, JavaScript, etc., where no such parameter is declared.
- Inside a method definition, always access attributes (that is, members of the instance or its class) with dot syntax, as in "self.spam".
- Yes, that's different from C++ and friends, where sometimes "spam" means "this->spam" (or "this.spam", in some languages) as long as it's not ambiguous. In Python, it never means "self.spam".
- When calling a method, on an object as in "breakfast.eat(9)", the object is passed as the first ("self") argument.
- Yes, that's different from C++ and friends, where instead of being passed normally as a first argument it's hidden under the covers and accessible through a magic "this" keyword.
Exceptions to the rules
Most of these should never affect novices, but it's worth putting them all in one place, from most common to least:
- When calling a method on the class itself, instead of on one of its instances, as in "Meal.eat(breakfast, 9)", you have to explicitly pass an instance as the first ("self") argument ("breakfast" in the example).
- A bound method, like "breakfast.eat", can be stored, passed around, and called just like a function. Whenever it's eventually called, "breakfast" will still be passed as the first "self" argument.
- An unbound method, like "Meal.eat", can also be stored, passed around, and called just like a function. In fact, in 3.0+, it is just a plain old function. Whenever it's eventually called, you still need to pass an instance explicitly as the first "self" argument.
- @classmethods take a "cls" parameter instead. Whether you call these on the class itself, or on an instance of the class, the class itself gets passed as the first ("cls") argument. These are often used for "alternate constructors", like datetime.now().
- @staticmethods do not take any extra parameter. Whether you call these on the class itself, or on an instance, nothing gets passed as an extra argument. These are almost never used.
- __new__ is always a @staticmethod, even though you don't declare it that way, and even though it actually acts more like a @classmethod.
- If you need to create a bound method explicitly for some reason (e.g., to monkeypatch an object without monkeypatching its type), you need to construct one manually using types.MethodType(func, obj, type(obj)).
What does a name name?
In a language like C++ or Java, when you type a variable name all by itself, it can mean one of many different things. At compile time, the compiler checks for a variety of different kinds of things that could be declared, in order, and picks the first matching declaration it finds. The rules are something like this (although not exactly the same in every related language):
- If you declared a variable with that name in the function definition, it's a local variable. (Actually, it's a bit more complicated, because every block in a C-family language is its own scope, but let's ignore that.)
- If you declared a static variable with that name in the function definition, it's a static variable. (These are globals in disguise, except that they don't conflict with other globals of the same name defined elsewhere.)
- If you declared a parameter with that name in the function definition, it's a function parameter. (These are basically the same as local variables.)
- If you declared a variable with that name in the function that the current local function is defined inside, it's a closure ("non-local") variable.
- If you declared a member with that name in the class definition, it's an instance variable. (Each instance has its own copy of this variable.)
- If you declared a class member with that name in the class definition, it's a class variable. (All instances of the class share a single copy of this variable, but each subclass has a different single copy for all of its instances.)
- If you declared a static member with that name in the class definition, it's a static class variable. (All instances of all subclasses share a single copy of this variable—it's basically a global variable in disguise.)
- Otherwise, it's a global variable.
If you use dot-syntax with "this", like "this.spam" (in C++, "this->spam"), or with the class, like "Meat.spam" (in C++, "Meat::spam"), you can avoid those rules and unambiguously specify the thing you want—even if there's a local variable named "spam", "this.spam" is still the instance variable.
Python doesn't have declarations. This means you don't have to write "var spam" all over the place as you do in JavaScript (or "const char * (Eggs::*Foo)(const char *)" as in C++) just to create local variables. Even better, you don't need to declare your class's instance variables anywhere; just create them in __init__, or any other time you want to, and they're members.
That gets rid of a whole lot of useless boilerplate in the code that doesn't provide much benefit. But it does mean you lose what little benefit that boilerplate would have provided—in particular, the compiler can't tell whether you wanted a global variable or an instance variable named "spam", because there's nowhere to check whether such an instance variable exists.
Therefore, when you're used to having a choice between "spam" and "this.spam", in Python you always have to write "self.spam". (And when you have a choice between "spam" and "Meat.spam", possibly with "this.spam" as an option, in Python you always have to write "Meat.spam", possibly with "this.spam" as an option.)
If you want to know why, you really need to read the article linked above. But briefly, besides the fact that the advantages of eliminating declarations are much bigger than the costs, "Explicit is better than implicit."
So, what rules does Python use for deciding what kind of variable a name names?
- If you list the variable name in a global statement, it's a global variable.
- If you list the variable name in a nonlocal statement (3.0+ only), it's a closure variable.
- If you assign to the variable name somewhere in the current function, it's local.
- If the variable name is included in the parameter list for the function definition, it's a parameter (meaning it's local).
- If the same name is a local or closure variable in the function the current function was defined inside, it's a closure variable.
- Otherwise, it's global.
Notice that, while a few of these (1, 2, and 4) are kind of similar to "declarations", the others (3, 5, and 6) are not at all the same. The fact that you don't accidentally get global variables when you forget to declare things (as in JavaScript) is another advantage of Python's way of doing things.
View comments