Need to declare an attribute in __init__

Asked

Viewed 128 times

-2

I was doing a Dice in python3, so far so good. but I don’t understand why I need to put the attributes in init, being that having them or not will work in the "same way" and I can’t see a "sense".

I learned Object Orientation with Java and there really things make more sense or I’m not understanding. Python’s Object Orientation is a bit confusing for me.

I’m sorry for the way I’m expressing/writing, maybe it sounds gross.

class Dado(object):
    def __init__(self, cor="vermelho", lado=6):
      self._cor = cor

    def setCor(self, cor):
      self._cor = cor


     def getCor(self):
      return self._cor

or

class Dado(object):
    def __init__(self):
      pass

    def setCor(self, cor):
      self._cor = cor

    def getCor(self):
      return self._cor

Why do I need to declare an attribute in init? or why this is necessary?

Like, it works both ways.

1 answer

-1


There is no written rule that you should declare the rules in your init() It’s just a matter of convention. When you declare the variables in init it is the equivalent of declaring their variables in the constructor. About your question:

Por que eu preciso declarar um atributo no init? ou por que isso é necessário?

It is not necessary to declare an attribute in init. It is not necessary. Everything works normal. This only serves as a shortcut to create an instance of your class in a more declarative way, or even to set default values at class startup.

The equivalent of this statement you made in java python would be:

//classe
class Dado {
     private String cor;
     private int lado;
     //construtor padrão do java não precisa ser declarado sempre vai existir 
     //public Dado(){
     //}
     //construtor 2
     public Dado(String cor, int lado) {
         this.cor = cor == null ? "vermelho" : cor;
         this.lado = lado == 0 ? 6 : lado
     }
     //getters e setters
}

But I would like to point out that it is not necessary to have the second constructor, because we will always have the default constructor of java, without parameters. Declaring a variable in the init method is equivalent to declaring a variable in the java constructor. Only this but the constructor is not required, everything works normal without declaring variables in the constructor.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.