我正在尝试编写一个类来显示正方形的宽度,它将处理传递负数的异常。
class Square:
def __init__(self,width):
try:
self.width = width
except ValueError:
print("Width cannot be less than zero.")
def __repr__(self):
return 'Square({0})'.format(self.width)
def __str__(self):
return "Square(" + str(self.width) + ")"
此时此代码将为正输入提供正确的输出,但是没有处理异常,而是输入了例如-10,代码给了我Square(-10)
。我似乎无法看出什么是错的。
答案 0 :(得分:3)
您的try块没有捕获错误,因为将变量赋值为负值没有任何问题。您需要自己检查并提出相应的错误。
def __init__(self, width):
if width < 0:
raise ValueError('Width cannot be less than zero.')
self.width = width
答案 1 :(得分:2)
这是因为否定width
是有效数字,并将其分配给self.width
不会引发ValueError
。您可以执行简单的if
检查,而不是处理异常。
def __init__(self, width):
if width < 0:
print('Width cannot be less than zero.')
else:
self.width = width
答案 2 :(得分:2)
Python并不关心width
是否为零。你必须要处理这个问题。
你可以用这种方式重写你的代码。
class Square:
def __init__(self,width):
try:
if width < 0:
raise ValueError("Negative value of width")
self.width = width
except ValueError:
print("Width cannot be less than zero.")
def __repr__(self):
return 'Square({0})'.format(self.width)
def __str__(self):
return "Square(" + str(self.width) + ")"
答案 3 :(得分:2)
你可以使用assert来引发错误:assert width>0,'error'
答案 4 :(得分:2)
你可以试试这个
class Square:
def __init__(self,width):
try:
if width < 0:
raise ValueError
self.width = width
except ValueError:
print("Width cannot be less than zero."),
print "Width is : %d" %width
def __repr__(self):
return 'Square({0})'.format(self.width)
def __str__(self):
return "Square(" + str(self.width) + ")"
obj = Square(10) # pass positive value
obj = Square(-10) # pass negative value
答案 5 :(得分:2)
这个怎么样:
self.width = width
if self.width < 0:
raise ValueError('Width cannot be less than zero.')