如何在Python中捕获NameError?
我一直在尝试用python编写一个简单的程序来使用类和测试属性。它要求用户输入其中一个名称,并使用该输入显示名称的两个属性。我尝试包含一个try…except块,以捕获在键入未定义为对象名称的内容时发生的NameError,但我仍然得到以下回溯:如何在Python中捕获NameError?,python,class,Python,Class,我一直在尝试用python编写一个简单的程序来使用类和测试属性。它要求用户输入其中一个名称,并使用该输入显示名称的两个属性。我尝试包含一个try…except块,以捕获在键入未定义为对象名称的内容时发生的NameError,但我仍然得到以下回溯: Traceback (most recent call last): File "C:/Users/Bede/Documents/Technology/Programming/Python/276/testcode", line 18, in
Traceback (most recent call last):
File "C:/Users/Bede/Documents/Technology/Programming/Python/276/testcode", line 18, in <module>
animalName = input(">")
File "<string>", line 1, in <module>
NameError: name 'Marmadukke' is not defined
我猜你在用python2.x。在这种情况下,您应该使用
raw\u input
而不是input
。问题是,在python2.x上,input
对您输入的数据调用eval
。我想,这意味着您可以将数据作为“Marmaduke”
(注意引号)输入。但是,根据您使用的是python2.x还是3.x,让程序的行为有所不同似乎是不可取的
使代码同时适用于python2.x和python3.x的简单方法:
try:
raw_input
except NameError:
raw_input = input
animalName=input(“>”)
在try块之外。这样错误就不会被发现
可能您希望在循环中的try块中:
while 1:
try:
animalName = input(">")
if isinstance(animalName,Cat):
这条线就是罪魁祸首:
animalName = input(">")
当您输入尚未定义的Marmadukke
时,会出现名称错误,因为您正在尝试执行以下操作:
animalName = Marmadukke #Not defined.
将其包装在try/except
块中:
try:
animalName = input(">")
except:
print("Invalid input!")
但要实现这一点,最好将动物存储到字典中,只检索名称:
animals = {}
animals['Marmaduke'] = Cat("Marmaduke",True)
animals['Timmy'] = Cat("Timmy",False)
animals['Cerberus'] = Dog("Cerberus",True)
animals['Max'] = Dog("Max",False)
以及检索:
animalName = animals[raw_input(">")]
然后,您可以将其放在while函数中,并捕获KeyError
,而不是NameError
希望这有帮助 为了好玩和有趣,我扩展了你的代码;试着追踪它,你会学到很多;-)
animalName = animals[raw_input(">")]
class Mammal(object):
index = {}
def __init__(self, name, chases_what=type(None)):
Mammal.index[name] = self
self.name = name
self.chases_what = chases_what
def speak(self):
pass
def chase(self, who):
if isinstance(who, self.chases_what):
self.speak()
print('{} chases {} the {}'.format(self.name, who.name, who.__class__.__name__))
who.speak()
else:
print("{} won't chase a {}".format(self.name, who.__class__.__name__))
class Mouse(Mammal):
def speak(self):
print('Squeak! Squeak!')
class Cat(Mammal):
def __init__(self, name, chases=True):
super(Cat, self).__init__(name, Mouse)
self.chases = chases
def chase(self, who):
if self.chases:
super(Cat, self).chase(who)
else:
print("{} won't chase anything".format(self.name))
class Dog(Mammal):
def __init__(self, name, chases_what=Cat):
super(Dog, self).__init__(name, chases_what)
def speak(self):
print('Bark! Bark!')
def chase(self, who):
if self is who:
print("{} chases his own tail".format(self.name))
else:
super(Dog, self).chase(who)
# create animal instances
Mouse('Jerry')
Mouse('Speedy Gonzalez')
Cat('Garfield', chases=False)
Cat('Tom')
Dog('Max')
Dog('Marmaduke', (Cat, Mouse))
def main():
while True:
name = raw_input('Enter an animal name (or Enter to quit): ').strip()
if not name:
break
me = Mammal.index.get(name, None)
if me is None:
print("I don't know {}; try again!".format(name))
continue
chase = raw_input('Enter who they should chase: ').strip()
target = Mammal.index.get(chase, None)
if target is None:
print("I don't know {}".format(name))
else:
me.chase(target)
if __name__=="__main__":
main()