如何在Python 3.7类中避免使用nameerror? [英] How do I avoid nameerror in Python 3.7 class?
问题描述
我正在尝试编写一个程序,其中except子句将在参数错误时运行,但是当我给出非有效参数时我得到NameError。我希望只在参数正确时才运行print函数但即使参数错误也在运行,所以我收到错误。
有谁能建议如何在不收到错误的情况下获得输出?
我的代码是:
class酒店:
def __init __(self,room,catagory):
if type(room)!= int:
raise TypeError()
if type(catagory)!= str:
raise TypeError()
self.room = room
self.catagory = catagory
self.catagories = {A:Elite,B:经济,C:常规}
self.rooms = [ 0,1,2,3,4,5]
def getRoom(self):
返回self.room
def getCatagory(个体经营):
返回self.catago ries.get(self.catagory)
def __str __(self):
返回%s和%s%(self.rooms [self.room],self.catagories.get(self.catagory) ))
试试:
room1 =酒店(a,A)
除外:
print(有错误)
打印(room1)
我的尝试:
我试图在except条件的内部和外部缩进打印行,但两种方式都没有。
如果你看一下上一篇文章:
如果用户提供错误的输入(不使用isinstance),如何捕获错误消息? [ ^ ],它解释了如何使用演示显示详细错误消息。
以下行会给出错误NameError:name'a'未在xx行定义
room1 =酒店(a,A)
以下行将给出错误TypeError:on line xx
room1 =酒店('a',A)
如您所见,第一行是抱怨a
不是有效变量而且它不会调用Hotel
class
第二行,调用Hotel
类并抛出类型错误。< br $> b $ b
8。错误和例外 - Python 3.7.2文档 [ ^ ]
I am trying to write a program where the "except clause will run when the parameters are wrong but I am getting NameError when I am giving non-valid parameter. I wanted the print function to be run only when the parameters are correct but it is running even if the parameters are wrong and so I am getting error.
Can anyone suggest how can I get the output without getting the error?
My code is:
class Hotel: def __init__(self,room,catagory): if type(room) != int: raise TypeError() if type(catagory) != str: 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.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") except: print("there's an error") print (room1)
What I have tried:
I have tried to indent the print line inside and outside of the except condition but neither of the way worked.
if you look at the previous post:
How do I catch the error message if the user gives wrong input (without using isinstance)?[^], it explain how to display the detail error message with a demo.
the below line will give the error "NameError: name 'a' is not defined on line xx"
room1 = Hotel(a,"A")
the below line will give the error "TypeError: on line xx"
room1 = Hotel('a',"A")
As you can see, the first line is complaining abouta
is not a valid variable and it doesn't call theHotel
class
The second line, call theHotel
class and throw type error.
8. Errors and Exceptions — Python 3.7.2 documentation[^]
这篇关于如何在Python 3.7类中避免使用nameerror?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!