为什么在运行类程序时出现此NameError错误?

时间:2020-05-13 11:32:36

标签: python oop

class Animal: 

    def __init__(self,name):
        self.name=name

    def sound(self):
        return 'this is animal sound'

    class Dog(Animal):
        def __init__(self,name, breed):
            super().__init__(name)
            self.breed=breed

    class Cat(Animal):
        def __init__(self,name,breed):
            super().__init__(name)
            self.breed=breed

doggy=Dog('Tomy','pug')
print(doggy.sound())

它显示了以下错误:

----------
Traceback (most recent call last):
  File "exception_handlin_2.py", line 1, in <module>
    class Animal:
  File "exception_handlin_2.py", line 9, in Animal
    class Dog(Animal):
NameError: name 'Animal' is not defined

1 个答案:

答案 0 :(得分:1)

缩进。 DogCat的类定义应低1个缩进。

class Animal: 

    def __init__(self,name):
        self.name=name

    def sound(self):
        return 'this is animal sound'

class Dog(Animal):
    def __init__(self,name, breed):
        super().__init__(name)
        self.breed=breed

class Cat(Animal):
    def __init__(self,name,breed):
        super().__init__(name)
        self.breed=breed

doggy=Dog('Tomy','pug')
print(doggy.sound())