There are a lot of questions on StackOverflow asking "what's the deal with self?"

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): 
  1. 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.)
  2. 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.)
  3. 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.)
  4. 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.
  5. 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.)
  6. 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.)
  7. 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.)
  8. 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?
  1. If you list the variable name in a global statement, it's a global variable.
  2. If you list the variable name in a nonlocal statement (3.0+ only), it's a closure variable.
  3. If you assign to the variable name somewhere in the current function, it's local.
  4. If the variable name is included in the parameter list for the function definition, it's a parameter (meaning it's local).
  5. If the same name is a local or closure variable in the function the current function was defined inside, it's a closure variable.
  6. 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.
1

View comments

It's been more than a decade since Typical Programmer Greg Jorgensen taught the word about Abject-Oriented Programming.

Much of what he said still applies, but other things have changed. Languages in the Abject-Oriented space have been borrowing ideas from another paradigm entirely—and then everyone realized that languages like Python, Ruby, and JavaScript had been doing it for years and just hadn't noticed (because these languages do not require you to declare what you're doing, or even to know what you're doing). Meanwhile, new hybrid languages borrow freely from both paradigms.

This other paradigm—which is actually older, but was largely constrained to university basements until recent years—is called Functional Addiction.

A Functional Addict is someone who regularly gets higher-order—sometimes they may even exhibit dependent types—but still manages to retain a job.

Retaining a job is of course the goal of all programming. This is why some of these new hybrid languages, like Rust, check all borrowing, from both paradigms, so extensively that you can make regular progress for months without ever successfully compiling your code, and your managers will appreciate that progress. After all, once it does compile, it will definitely work.

Closures

It's long been known that Closures are dual to Encapsulation.

As Abject-Oriented Programming explained, Encapsulation involves making all of your variables public, and ideally global, to let the rest of the code decide what should and shouldn't be private.

Closures, by contrast, are a way of referring to variables from outer scopes. And there is no scope more outer than global.

Immutability

One of the reasons Functional Addiction has become popular in recent years is that to truly take advantage of multi-core systems, you need immutable data, sometimes also called persistent data.

Instead of mutating a function to fix a bug, you should always make a new copy of that function. For example:

function getCustName(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

When you discover that you actually wanted fields 2 and 3 rather than 1 and 2, it might be tempting to mutate the state of this function. But doing so is dangerous. The right answer is to make a copy, and then try to remember to use the copy instead of the original:

function getCustName(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

function getCustName2(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[2] + ' ' + custRec[3];
    return fullname;
}

This means anyone still using the original function can continue to reference the old code, but as soon as it's no longer needed, it will be automatically garbage collected. (Automatic garbage collection isn't free, but it can be outsourced cheaply.)

Higher-Order Functions

In traditional Abject-Oriented Programming, you are required to give each function a name. But over time, the name of the function may drift away from what it actually does, making it as misleading as comments. Experience has shown that people will only keep once copy of their information up to date, and the CHANGES.TXT file is the right place for that.

Higher-Order Functions can solve this problem:

function []Functions = [
    lambda(custID) {
        custRec = readFromDB("customer", custID);
        fullname = custRec[1] + ' ' + custRec[2];
        return fullname;
    },
    lambda(custID) {
        custRec = readFromDB("customer", custID);
        fullname = custRec[2] + ' ' + custRec[3];
        return fullname;
    },
]

Now you can refer to this functions by order, so there's no need for names.

Parametric Polymorphism

Traditional languages offer Abject-Oriented Polymorphism and Ad-Hoc Polymorphism (also known as Overloading), but better languages also offer Parametric Polymorphism.

The key to Parametric Polymorphism is that the type of the output can be determined from the type of the inputs via Algebra. For example:

function getCustData(custId, x)
{
    if (x == int(x)) {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return int(fullname);
    } else if (x.real == 0) {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return double(fullname);
    } else {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return complex(fullname);
    }
}

Notice that we've called the variable x. This is how you know you're using Algebraic Data Types. The names y, z, and sometimes w are also Algebraic.

Type Inference

Languages that enable Functional Addiction often feature Type Inference. This means that the compiler can infer your typing without you having to be explicit:


function getCustName(custID)
{
    // WARNING: Make sure the DB is locked here or
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

We didn't specify what will happen if the DB is not locked. And that's fine, because the compiler will figure it out and insert code that corrupts the data, without us needing to tell it to!

By contrast, most Abject-Oriented languages are either nominally typed—meaning that you give names to all of your types instead of meanings—or dynamically typed—meaning that your variables are all unique individuals that can accomplish anything if they try.

Memoization

Memoization means caching the results of a function call:

function getCustName(custID)
{
    if (custID == 3) { return "John Smith"; }
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

Non-Strictness

Non-Strictness is often confused with Laziness, but in fact Laziness is just one kind of Non-Strictness. Here's an example that compares two different forms of Non-Strictness:

/****************************************
*
* TO DO:
*
* get tax rate for the customer state
* eventually from some table
*
****************************************/
// function lazyTaxRate(custId) {}

function callByNameTextRate(custId)
{
    /****************************************
    *
    * TO DO:
    *
    * get tax rate for the customer state
    * eventually from some table
    *
    ****************************************/
}

Both are Non-Strict, but the second one forces the compiler to actually compile the function just so we can Call it By Name. This causes code bloat. The Lazy version will be smaller and faster. Plus, Lazy programming allows us to create infinite recursion without making the program hang:

/****************************************
*
* TO DO:
*
* get tax rate for the customer state
* eventually from some table
*
****************************************/
// function lazyTaxRateRecursive(custId) { lazyTaxRateRecursive(custId); }

Laziness is often combined with Memoization:

function getCustName(custID)
{
    // if (custID == 3) { return "John Smith"; }
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

Outside the world of Functional Addicts, this same technique is often called Test-Driven Development. If enough tests can be embedded in the code to achieve 100% coverage, or at least a decent amount, your code is guaranteed to be safe. But because the tests are not compiled and executed in the normal run, or indeed ever, they don't affect performance or correctness.

Conclusion

Many people claim that the days of Abject-Oriented Programming are over. But this is pure hype. Functional Addiction and Abject Orientation are not actually at odds with each other, but instead complement each other.
5

View comments

Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.