首页 > 解决方案 > 如何从父类调用属性?

问题描述

我目前正在学习如何在 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'"

标签: python

解决方案


您需要在__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 在这里所做的。


推荐阅读