Search code examples
pythonpython-3.xgetter-setter

setter does not recognize ValueError


im trying to do a banck acc in python with getters and setters but the setter does not recognize the ValueError when I put str in saldo, however it is supposed to popup some error because this is just for int and float not for str

class Conta(Cliente):
    def __init__(self, nome, idade, cpf, agencia, conta, saldo):
        super().__init__(nome, idade, cpf)
        self._agencia = agencia
        self._conta = conta
        self.saldo = saldo
 
    @property
    def saldo(self):
        print('teste getter')
        return self._saldo
 
    @saldo.setter
    def saldo(self, value):
        print('test setter')
        if not isinstance(value, (int, float)):
            ValueError('value NEED to be a number!')
 
        self._saldo = value
 
cliente = Conta('leonardo', 1231,123123,1232,123123,saldo = 'it is supposed to print ValueError')

#output
test setter

Solution

  • You are missing the raise keyword before the name of the Exception to actually raise it, try the following code instead :

    if not isinstance(value, (int, float)):
        raise ValueError('value NEED to be a number!')
    

    Relevant Python documentation page: Errors and Exceptions - Raising Exceptions