Python 为什么在运行类程序时出现此名称错误?
它显示了以下错误:Python 为什么在运行类程序时出现此名称错误?,python,oop,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) s
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())
----------
回溯(最近一次呼叫最后一次):
文件“exception_handlin_2.py”,第1行,在
动物类别:
文件“exception_handlin_2.py”,第9行,动物版
犬类(动物):
NameError:未定义名称“Animal”
缩进。Dog
和Cat
的类定义应低1个缩进
----------
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
你能保证缩进是正确的吗?如前所述,
猫
和狗
嵌套在动物
类中?在类狗
和行首之间不应有任何间隔。同样的情况也适用于猫类,非常感谢。我已经纠正了压痕。它现在运行正常了。
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())