I'd like to raise a TypeError when the parameter of a method in a class is non-integer, but I failed. The code is as below, I put a "N" in the first parameter and expected to get a TypeError, and the printing of " can't set the Rectangle to a non-integer value ", but what I got instead is "Traceback (most recent call last): File "/Users/Janet/Documents/module6.py", line 19, in r1.setData(N,5) NameError: name 'N' is not defined"
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)
Consider using typeof, as in this question: Checking whether a variable is an integer or not
You have some bad formatting in your listing, by the way. Change this:
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
to this:
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
Edit answer to reflect the new and more accurate explanation. As @Evert says, N is not defined, so Python is looking what the variable N is, and it isn't finding anything. If you instead wrote "N" (making it a string), then your program should return 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)
This prints out: "can't set the Rectangle to a non-integer value height = 0, and width = 0"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.