我刚开始学习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.
继承不是这样的。你不能单独实例化它们;关键是您只实例化SpecificAttribute,它已经是GeneralAttribute了,因为继承是一种“is-a”关系
为了启用此功能,您需要从specificatribute one中调用GeneralAttribute
__init__
方法,您可以使用super
相关问题 更多 >
编程相关推荐