1
excuse my ignorance on the subject because I’m starting now in the Python language, and for this very reason I wanted to know what works the reserved word "self".
Thanks for your attention and patience!
1
excuse my ignorance on the subject because I’m starting now in the Python language, and for this very reason I wanted to know what works the reserved word "self".
Thanks for your attention and patience!
4
The reserved word self serves for you to refer to yourself
object(instance) both when you are going to use methods and when you are
use attributes belonging to and this object.
Dry up 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
On line (2) we initialize the Point Class and ask that two be passed
parameters (self, x) do not worry about the self, as python methods when
called pass the object(instance) as the first parameter, i.e., self is
a reference to the object in question itself. I know that it is difficult to assimilate
but think I’ll try to make it clear think with me:
A class is nothing more than a factory of objects ? I mean I can create
infinite objects, but as seen above I initialized two objects for the class
Point (object_1, object_2), when I decided to change the x of object_1 as the
interpreter knew what the object in question was ???
This is done thanks to the self that is always passed as the first parameter.
I’m sorry for stretching but I’ll do everything I can to help.
0
The reserved word self
is used as a reference to the same object.
recommend reading Significadodoself and Introducaooop
Browser other questions tagged python oop function method reserved-words
You are not signed in. Login or sign up in order to post.
Your paragraph is confused. You really wanted to write the way it’s being shown?
– Jefferson Quesado
Thanks for the friendly explanation!
– Matheus Grossi