当一个类中方法的参数是非整数时,我想引发一个TypeError,但是我失败了。代码如下,我在第一个参数中放了一个“N”,并期望得到一个TypeError,并打印“不能将Rectangle设置为非整数值”,但我得到的是“Traceback” (最近的电话最后一次): 文件“/Users/Janet/Documents/module6.py”,第19行,in r1.setData(N,5) NameError:名称'N'未定义“
class Rectangle:
def __init__ (self):
self.height = 0
self.width = 0
def setData(self, height, width):
if type(height) != int or type(width) != int:
raise TypeError()
if height <0 or width <0:
raise ValueError()
self.height = height
self.width = width
def __str__(self):
return "height = %i, and width = %i" % (self.height, self.width)
r1 = Rectangle()
try:
r1.setData(N,5)
except ValueError:
print ("can't set the Rectangle to a negative number")
except TypeError:
print ("can't set the Rectangle to a non-integer value")
print (r1)
答案 0 :(得分:0)
考虑使用typeof,如此问题:Checking whether a variable is an integer or not
顺便提一下,您的商家信息中有一些不良格式。改变这个:
def setData(self, height, width):
if type(height) != int or type(width) != int:
raise TypeError()
if height <0 or width <0:
raise ValueError()
self.height = height
self.width = width
到此:
def setData(self, height, width):
if type(height) != int or type(width) != int:
raise TypeError()
if height <0 or width <0:
raise ValueError()
self.height = height
self.width = width
答案 1 :(得分:0)
编辑答案以反映新的更准确的解释。 正如@Evert所说,N未定义,因此Python正在查看变量N是什么,并且它没有找到任何东西。如果你改为写“N”(使它成为一个字符串),那么你的程序应该返回TypeError。
class Rectangle:
def __init__ (self):
self.height = 0
self.width = 0
def setData(self, height, width):
if type(height) != int or type(width) != int:
raise TypeError()
if height <0 or width <0:
raise ValueError()
self.height = height
self.width = width
def __str__(self):
return "height = %i, and width = %i" % (self.height, self.width)
r1 = Rectangle()
try:
r1.setData("N",5)
except ValueError:
print ("can't set the Rectangle to a negative number")
except TypeError:
print ("can't set the Rectangle to a non-integer value")
print (r1)
打印出: “无法将Rectangle设置为非整数值 height = 0,width = 0“