handle
handle

Reputation: 6329

Inheritance and object copies

I'd like a Derived object to also "inherit" data from a Base object - how would that be done?

#!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'

Upvotes: 0

Views: 46

Answers (1)

Sraw
Sraw

Reputation: 20224

This seems not a problem about "inherit", you just want to merge the data from another object.

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)

Upvotes: 1

Related Questions