简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM