【问题标题】:Does anyone know why the ValueErrorException is not showing?有谁知道为什么没有显示 ValueError 异常?
【发布时间】:2023-09-05 00:55:01
【问题描述】:
class ValueErrorException(Exception):
pass
class BankAccount(object):
def __init__(self, balance):
self.balance = balance
def balance(self):
if self.balance<0:
raise ValueErrorException("Illegal Balance")
else:
return self.balance
x = BankAccount(-10)
print(x.balance)
应该打印错误,但它打印 -10。我究竟做错了什么?
【问题讨论】:
标签:
python
object
exception
valueerror
【解决方案1】:
您为此BankAccount 类定义了一个属性.balance 和一个方法.balance()。因为它们具有相同的名称,所以一个会覆盖另一个。确保它们具有单独的名称,例如:
class BankAccount(object):
def __init__(self, balance):
self._balance = balance
def balance(self):
if self._balance<0:
raise ValueErrorException("Illegal Balance")
else:
return self._balance
然后调用你的.balance() 方法(注意括号):
>>> x = BankAccount(-10)
>>> print(x.balance())
这应该引发所需的异常。
【解决方案2】:
在 init 中,您将值 -10 分配给 self.balance,您从不调用方法 balance()。您可能想要的是使用属性和设置器。这样,每次为 balance 分配一个值时,都会执行一次检查:
class BankAccount(object):
def __init__(self, balance):
self.balance = balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("Illegal Balance")
self._balance = value
另外,ValueError 是 python 内置的异常,你不需要自己的 Exception 类。