Although in another language, this question was answered in STO itself . So I just made one adptation:
The reason you need to use the self is because Python does not use @ syntax to refer to instance attributes.
The Python team decided to make methods in a way that causes the instance to which the method belongs to be passed automatically but not received automatically: The first parameter of a method is the instance where the method is called. / p>
This causes the methods to be entirely equal to the functions, and leaves the actual name to be used, at the user / developer's charge (although the word self
is convention and most of people will twist their nose if you use any other word).
Edited
Example avoiding self
(do not twist your nose!) :-)
Note: I ran in a (local) python 3 terminal, in the repl.it was not accepted, it requires 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 distinguish "normal names" from attributes - Special syntax like Ruby, or require statements like C ++ and Java, or perhaps something else - SQN. / p>
Python has as one of the pillars of its philosophy the determination to do things as explicitly as possible, although of course this goal can not always be achieved.
As a consequence of this goal, you need self
, to assign to an instance attribute, explicit to which instance to assign, self
informs you that the assignment is the yourself.