2017-05-09 43 views
0

DerivedオブジェクトもBaseオブジェクトからデータを「継承」したいと思います。継承とオブジェクトのコピー

+3

あなたが使用するかどうかを決定すべきである[構成](https://en.wikipedia.org/wiki/Object_composition)または[継承](https://en.wikipedia.org/wiki/Inheritance_ (オブジェクト指向プログラミング))。今、あなたは両方をやろうとしていますが、それは本当に意味をなさないものです。継承で正常に行われたいくつかのことを達成するために合成を使用する[継承上の合成](https://en.wikipedia.org/wiki/Composition_over_inheritance)も参照してください。 – Kevin

答えて

1

これは「継承」についての問題ではないように、別のオブジェクトのデータをマージしたいだけです。

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) 
+0

これは、データ(属性)を「深層コピー」し、_composition_カテゴリに該当しますか? – handle

+0

@handleあなたが正しいと思われます。私はあなたの基本クラスが属性だけを持っているが機能はないと思う、それはクラスから遠く離れているがコンテナと似ている。 – Sraw

関連する問題