如何在Python中捕获NameError?

时间:2013-12-08 00:31:51

标签: python class

我一直在尝试在python中编写一个简单的程序来使用类和测试属性。它要求用户输入其中一个名称,并使用该输入显示名称的2个属性。我试图包含一个try ... except块来捕获在键入未被定义为对象名称的东西时发生的NameError,但我仍然得到这个回溯:

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

我知道这可能不是最好的做事方式,所以我对所有建议持开放态度。

我的完整代码在这里:

class Dog(object):
    def __init__(self,name,chasesCats):
        self.name = name
        self.chasesCats = chasesCats

class Cat(object):
    def __init__(self,name,chasesMice):
        self.name = name
        self.chasesMice = chasesMice

Marmaduke = Cat("Marmaduke",True)
Timmy = Cat("Timmy",False)
Cerberus = Dog("Cerberus",True)
Max = Dog("Max",False)

print("Enter Marmaduke, Timmy, Max or Cerberus.")

animalName = input(">")
while 1:
    try:
        if isinstance(animalName,Cat):
            print("Cat")
            if animalName.chasesMice:
                print("Chases mice")
            else: print("Doesn't chase mice")
        if isinstance(animalName,Dog):
            print("Dog")
            if animalName.chasesCats:
                print("Chases cats")
            else: print("Doesn't chase cats")
        break
    except NameError:
            print("Try again!")

4 个答案:

答案 0 :(得分:4)

我猜你正在使用python2.x。在这种情况下,您应该使用raw_input而不是input。问题是在python2.x上,input会对您输入的数据调用eval。我想,这意味着您可以将数据放入{{1} (注意引号)。但是根据你使用的是python2.x还是3.x,程序的行为会有所不同。

使代码适用于python2.x和python3.x的简单方法:

"Marmaduke"

答案 1 :(得分:2)

animalName = input(">")在try块之外。所以错误不会被捕获。

可能你想在循环中的try块中找到它:

while 1:
    try:
        animalName = input(">")
        if isinstance(animalName,Cat):

答案 2 :(得分:1)

这条线是罪魁祸首:

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

希望这有帮助!

答案 3 :(得分:1)

为了娱乐和兴趣,我扩展了你的代码;尝试追踪它,你应该学到很多东西; - )

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()