setter 无法识别 ValueError

setter does not recognize ValueError

我正在尝试使用 getter 和 setters 在 python 中执行 banck acc,但是当我将 str 放入 saldo 时 setter 无法识别 ValueError,但是它应该是弹出一些错误,因为这仅适用于 int 和 float,不适用于 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

您在 Exception 的名称之前缺少 raise 关键字以实际引发它,请尝试使用以下代码:

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

相关 Python 文档页面:Errors and Exceptions - Raising Exceptions