继承和对象副本

时间:2017-05-09 16:07:42

标签: python

我希望Derived对象也能继承"继承"来自Base对象的数据 - 如何做?

#!python3
#coding=utf-8

class Base:
    def __init__(self, attrib):
        self.attrib = attrib

listOfBaseObjects = [
    Base("this"),
    Base("that"),
    ]

print(listOfBaseObjects)

import copy

class Derived(Base):                        # ?
    def __init__(   self, baseObject,       # ?
                    otherattrib):
        #Base.__init__(baseObject)           # ?
        #self = copy.copy(baseObject)        # ?
        self.otherattrib = otherattrib

    def __repr__(self):
        return "<Derived: {} {}>".format(self.attrib, self.otherattrib)

listOfDerivedObjects = [
    Derived(listOfBaseObjects[0], "this"),
    Derived(listOfBaseObjects[1], "that"),
    ]


print(listOfDerivedObjects)
# AttributeError: 'Derived' object has no attribute 'attrib'

1 个答案:

答案 0 :(得分:1)

这似乎不是&#34;继承&#34;的问题,您只想合并来自另一个对象的数据。

class Base:
    def __init__(self, attrib):
        self.attrib = attrib

listOfBaseObjects = [
    Base("this"),
    Base("that")
    ]

print(listOfBaseObjects)

class Derived():                        
    def __init__(self, baseObject, otherattrib):
        for key, value in vars(baseObject).items():
            setattr(self, key, value)
        self.otherattrib = otherattrib

    def __repr__(self):
        return "<Derived: {} {}>".format(self.attrib, self.otherattrib)

listOfDerivedObjects = [
    Derived(listOfBaseObjects[0], "this"),
    Derived(listOfBaseObjects[1], "that"),
    ]


print(listOfDerivedObjects)