Although in another language, this question was answered in STO itself. So I just did an assignment:
The reason you need to use the self is because Python does not use the syntax @ to refer to the attributes of instances.
The Python team decided to make methods in a way that causes the instance to which the method belongs to to to be passed automatically, but not received automatically: The first parameter of a method is the instance where the method is called.
This makes the methods entirely equal to the functions, and leaves the real name to be used, in charge of the user/developer (although the word self
be the convention and most people will turn their nose if you use any other word).
Edited
Example avoiding the self
(don’t twist your nose!) :-)
Obs. I circled in a python 3 (local) terminal, no repl it. was not accepted, demands the self
class Foo():
def __init__(this, msg):
this.msg = msg
@property
def bar(this):
return 'Hello '+this.msg
foo = Foo('bar')
foo.bar
'Hello bar'
self
There’s nothing special about the code, it’s just another object.
Python developers could have opted for another strategy to distigure "normal names" from attributes -- Special syntax like Ruby, or require statements like C++ and Java or perhaps anything else-- SQN.
Python has as one of the pillars of his philosophy the determination to do things as explicitly as possible, although obviously this goal may not always be achieved.
As a consequence of this goal, Voce needs the self
, to make an assignment to an instance attribute, it is necessary to spell out to which instance to assign, self
informs that the assignment is itself.
Explicit is Better than implicit
– bfavaretto
@bfavaretto found this philosophy cool, but still do not see the pq of self...rs
– Zeca
To better understand the question: how would you write something with this same structure in JS, since you said you use Node?
– bfavaretto