python - 为什么我在运行我的类程序时收到此 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
解决方案
缩进。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())
推荐阅读
- aws-serverless - 我的无服务器部署包超过 100 MB,SLS 命令拒绝部署它
- php - 我尝试在 laravel 上使用 postgresql 但找不到驱动程序(SQL: select * from "users" where "id" = 4 limit 1)
- printing - 我想用 N 个并行进程打印 1 到 11、2 到 22 等
- c++ - 从 C++ 中的自定义异构容器打印
- pandas - pandas:在多列中找到字符串后获取下一列的值
- c++ - 多重定义错误#include -ing .h 标头
- google-bigquery - 从 GCS (load_table_from_uri) 将数据加载到 BigQuery - 最大文件?
- vector - Inkscape 矢量填充图案的语法
- python - 获取 TypeError:列表索引必须是整数或切片,而不是运行此代码时的 str
- python-3.x - PI 4b 上的 RPi.GPIO 问题