What is the word "self" for in Python? [duplicate]
Sorry for my ignorance on the subject because I am starting now in the Python language, and for that very reason I wanted to know what the reserved word "self"works for.
From now on I thank you for your attention and patience!
2 answers
The reserved word self is for you to reference
Object (instance) both when you are making use of methods and when you are
Use attributes belonging to and this object.
Dry the example:
class Ponto(object): #(1)
def __init__(self, x): #(2)
self.x = x #(3)
def set_x(self, valor): #(4)
self.x = valor #(5)
objeto_1 = Ponto(2) # inicilizamos um objeto com x = 2
objeto_2 = Ponto(3) # inicializamos outro objeto com x = 4
print(objeto_1.x) # imprime o valor de x do objeto_1 que é 2
objeto_1.set_x(7) # alteramos o valor x de objeto_1 para 7
print(objeto_1.x) # imprime o valor de x do objeto_1 que é 7
objeto_2.set_x(5) # alteramos o valor de x do objeto_2 para 5
print(objeto_2.x) # imprime o valor de x do objeto_2 que é 5
In line (1) we create the point Class
In line (2) we initialize the Point class and ask that two
Parameters (self, x) don't worry about self, because Python methods when
Called pass the object (instance) as the first parameter, i.e. self is
A reference to the object itself in question.I know it's hard to assimilate
But think I'll try to make it clear Think With Me:
A class is nothing more than a factory of objects right ? I. e. i can create
Infinite objects, but as seen above I initialized two objects to Class
Point (object_1, object_2), when I decided to change the X of object_1 as the
Interpreter did you know what the object was ???
This is done thanks to self which is always passed as the first parameter.
I'm sorry to stretch out, but I'll do everything I can to help.
The reserved word self
is used as the reference of the same object.
I recommend reading Meaningself and Introduceooop