Why use the __init__ constructor method in Python? [duplicate]

0

I would like to understand better why using __init__ by comparing these two code, I even understood that __init__ will always be started with the instantiated object, but should I always use it?

With __init__:

class Cliente():
    def __init__(self,saldo,nome):
        self.__saldo = nome
        self.__nome = saldo
    def getsaldo(self):
        return self.__saldo
    def setsaldo(self,saldo):
        self.__saldo = saldo
    def setnome(self,nome):
        self.__nome = nome
    def getnome (self):
        return self.__nome

No __init__:

class Cliente():
    __saldo = 0
    __nome = None
    def getsaldo(self):
        return self.__saldo
    def setsaldo(self,saldo):
        self.__saldo = saldo
    def setnome(self,nome):
        self.__nome = nome
    def getnome (self):
        return self.__nome
    
asked by anonymous 18.09.2018 / 18:47

1 answer

-1

Come on, the init method of python is nothing more than the constructor of a class. This method is fired whenever "import" is given in a class. What's more, it allows you to feed attributes to even call functions. In your example above with " init " you can feed the "__name and __saldo" attributes each time you instantiate the class. If you do not use it, the only way to change these values is to just call a method so that you can then change these properties.

I hope it has cleared up.

    
18.09.2018 / 19:13