类继承[初学者]

2024-09-30 18:19:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始学习Python,我担心我不理解类和继承的正确用法。在下面的代码中,我尝试创建一个类来定义项的常规属性。然后我想使用另一个类添加更多属性,同时保留先前定义的项属性

class GeneralAttribute :

    def __init__(self, attribute1, attribute2, attribute3) :
        self.Attribute1 = attribute1
        self.Attribute2 = attribute2
        self.Attribute3 = attribute3

class SpecificAttribute(GeneralAttribute) :

    def __init__(self, attribute4, attribute5, attribute6, attribute7) :
        self.Attribute4 = attribute4
        self.Attribute5 = attribute5
        self.Attribute6 = attribute6
        self.Attribute7 = attribute7

item = GeneralAttribute(7, 6, 5)
item = SpecificAttribute(1, 2, 3, 4)

print item.Attribute1 
# This leads to an error since Attribute1 is no longer defined by item.

Tags: self属性定义initdefitemclassattribute1
1条回答
网友
1楼 · 发布于 2024-09-30 18:19:09

继承不是这样的。你不能单独实例化它们;关键是您只实例化SpecificAttribute,它已经是GeneralAttribute了,因为继承是一种“is-a”关系

为了启用此功能,您需要从specificatribute one中调用GeneralAttribute__init__方法,您可以使用super

class SpecificAttribute(GeneralAttribute) :

    def __init__(self, attribute1, attribute2, attribute3, attribute4, attribute5, attribute6, attribute7):
        super(SpecifcAttribute, self).__init__(attribute1, attribute2, attribute3)
        self.Attribute4 = attribute4
        self.Attribute5 = attribute5
        self.Attribute6 = attribute6
        self.Attribute7 = attribute7

item = SpecificAttribute(1, 2, 3, 4, 5, 6, 7)

相关问题 更多 >