首页 > 解决方案 > 为什么我在运行我的类程序时收到此 NameError?

问题描述

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

标签: pythonoop

解决方案


缩进。Dog和的类定义Cat应该低 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())

推荐阅读