What is the word "self" in Python? [duplicate]

0

Excuse my ignorance on the subject because I'm starting now in the Python language, and for that same reason I wanted to know what the reserved word "self" works for.

I thank you for your attention and patience!

    
asked by anonymous 20.10.2017 / 04:48

2 answers

2

The reserved word self is for you to refer to yourself

object (instance) both when you are going to use methods as it is

use attributes belonging to 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 we ask that two

Parameters (self, x) do not worry about the self, since methods in python when

called pass the object (instance) as the first parameter, that is, self is

A reference to the object itself. I know it is difficult to assimilate.

But I'm going to try to make this clear think with me:

A class is nothing more than a factory of objects, right? In other words, I can create

20.10.2017 / 06:34
0

The reserved word self is used as a reference for the same object. I recommend reading Meaning of Self and IntroductionOop

    
20.10.2017 / 05:36