Louis I. answered 05/11/20
Computer Science Instructor/Tutor: Real World and Academia Experienced
I asked the same question when I first started learning Python, and that was when I
had considerable coding experience, so I understand the confusion.
Other OO languages like C++ and Java have an omnipresent reference called "this",
which always refers to "the current object", but DOESN'T need to be explicitly
defined in every method signature.
So if we're implementing a method that needs to reference a data or method member of that
object, "this" would be used to fully qualify that reference.
For example in Java, if we needed to assign 128 to an int data member called 'x',
we would code as follows:
this.x = 128;
Using "this" to fully qualify 'x' above might be required to differentiate it from
another variable/reference 'x' declared in local scope, OR "this" might be used
optionally just to highlight that 'x' is a member of the current object.
In Python, "self" is essentially equivalent to "this" in C++/Java,
except that the Python architects decided to be more explicit
about what's going on here.
When an object method/function is invoked, the instance itself
is transparently passed in as the 1st attribute.
See partial example of a "Calculator" class below (limited to
addition and subtraction).
"self" needs to be defined as the 1st argument in every method ....
class Calculator(object):
__value__ = 0
__valueHistory__ = []
def add(self, number):
self.__valueHistory__.append(self.__value__)
self.__value__ += number
def sub(self, number):
self.__valueHistory__.append(self.__value__)
self.__value__ -= number
... but when we use an instance of Calculator and invoke its methods,
"self" is not included in the method signature.
## Create an instance of the Calculator Class
calc = Calculator()
## add 5 to the calc (5)
calc.add(5)
## subtract 2 from the calc (3)
calc.sub(2)
I have read through many explanations of the "self" reference in Python.
What it is and how it works is quite clear, but why Python language
designers forced its declaration in every object method is not explained beyond,
"Explicit is better than implicit".
One of the better overviews of this topic appears here -> www.programiz.com/article/python-self-why
Clearly, the language could have not mandated its inclusion in every method signature ....