The need for self in Python

In Python, you need to take a first argument, which is traditionally called self in all instance methods, including the constructor. The object upon which the method is being called is automatically passed as this argument. This is for the following reasons:

  • Python doesn’t require the declaration of member variables as languages like C++ or Java do, so without self there would be no way of knowing that an unqualified name was the name of a member
  • Similarly, Python doesn’t have Ruby’s @ prefix to distinguish members

I think it also has the following advantages:

  • Requiring self has the advantage over C++ and Java of making it clear that the variable is a member, which often isn’t clear in those languages, requiring you to look at the class declaration to find out, and possibly using prefixes like m_ on members to make it clear
  • It also has the advantage of distinguishing member names from global names, which in C++ you need to do using the :: scope resolution operator in front of the name