[英]How do you raise ValueError for input valuable in Python class?
I want to raise an Value Error for negative values of a and b.我想为 a 和 b 的负值引发值错误。 I have played around with this but it raises ValueError for different values and it does not seem to work properly.
我玩过这个,但它为不同的值引发了 ValueError 并且它似乎无法正常工作。
class RightTriangle:
def __init__(self, a, b):
self.a = a
self.b = b
self.c = np.sqrt(a**2+b**2)
if (self.a or self.b) < 0:
raise ValueError("Negative")
Fix:使固定:
if self.a < 0 or self.b < 0:
What you've got is evaluating (self.a or self.b)
first.您首先要评估
(self.a or self.b)
。 What this first part is doing is this:第一部分正在做的是:
if self.a: # anything but 0 is True
return self.a
else:
return self.b
So, you're probably going to get self.a
most of the time, and then it's going to be compared in < 0
.所以,大部分时间你可能会得到
self.a
,然后它会在< 0
进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.