python - 如何从父类调用属性?
问题描述
我目前正在学习如何在 Python 中编程我被困在从 Parent 类中调用一个属性。在下面的示例中,如何调用"name"
“daisy”上的属性来打印名称。我总是得到一个错误"'Mammal' object has no attribute 'name'
。
class Vertebrate:
spinal_cord = True
def __init__(self, name):
self.name = name
class Mammal(Vertebrate):
def __init__(self, name, animal_type):
self.animal_type = animal_type
self.temperature_regulation = True
daisy = Mammal('Daisy', 'dog')
print(daisy.name)
在这里我想打印已经在 Vertebrate 类中定义的名称,但总是报错
"'Mammal' object has no attribute 'name'"
解决方案
您需要在__init__
Mammal 中调用 super,如下所示:
class Mammal(Vertebrate):
def __init__(self, name, animal_type):
super().__init__(name)
self.animal_type = animal_type
self.temperature_regulation = True
当__init__
Mammal 被调用时,它不会自动调用__init__
它的父类,这就是 super 在这里所做的。
推荐阅读
- html - css 边距推动体
- python - 多次检查空数据框
- ruby-on-rails - 定义 Rails 迁移方法的合适位置在哪里?
- firebase - 在 Unity Firebase 中更改用户字段
- java - 云存储 - 上传图像时文件的内容类型显示为数据
- docker - 我无法在 google/cloud-sdk 映像中使用 docker 命令
- javascript - 如何使用 Axios 库发送 XML 数据
- python - cx_Freeze 可执行文件不显示 matplotlib 数字
- react-native - 检测本机反应中的系统语言变化
- python - Python dict 自动将列表类型值转换为简单对象