我编写了一条代码,使用try和except捕获错误消息(我想不使用isinstance编写它),并且输入不是整数时,我会收到错误消息。问题是,即使输入是有效整数,程序也会给我错误消息。请给我一些建议以使其运行。我的代码如下:
我尝试使用异常子句,但这没用。
class Hotel:
def __init__(self,room,catagory):
if room != int:
raise TypeError ()
self.room = room
self.catagory = catagory
self.catagories = {"A":"Elite","B":"Economy","C":"Regular"}
self.rooms = ["0","1","2","3","4","5"]
def getRoom(self):
return self.room
def getCatagory(self):
return self.catagory
return self.catagories.get(self.catagory)
def __str__(self):
return "%s and %s"%(self.rooms[self.room],self.catagories.get(self.catagory))
try:
room1 = Hotel(a,"A")
room2 = Hotel(1,"A")
print(room1.getRoom())
except:
print("there's an error")
我期望:
有错误
1和精英
A
答案 0 :(得分:1)
您正在检查room != int
是否。它总是会给你错误。
您必须检查type(room)!= int
。
我已更正下面的代码
class Hotel:
def __init__(self,room,catagory):
if type(room) != int:
raise TypeError ()
self.room = room
self.catagory = catagory
self.catagories = {"A":"Elite","B":"Economy","C":"Regular"}
self.rooms = ["0","1","2","3","4","5"]