我想写一个类来显示正方形的宽度,它将处理传递负数的异常。我的代码没有处理异常(python)
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)
。我似乎无法看到有什么问题。
你的代码不仅适用于积极的,但也是负面的。 – itzMEonTV 2015-03-25 05:45:46
当你说'self.width = width'时,你有没有事情会导致异常?这里python不关心'width'是否为负值。你必须照顾这一点。 – niyasc 2015-03-25 05:45:54