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'
당신이 사용할 것인지 여부를 결정해야합니다 [구성] (https://en.wikipedia.org/wiki/Object_composition) 또는 [상속] (https://en.wikipedia.org/wiki/Inheritance_ (객체 지향 프로그래밍)). 지금 당장 당신은 두 가지를하려고 노력하고 있습니다. [상속을 통한 합성] (https://en.wikipedia.org/wiki/Composition_over_inheritance)도 참조하십시오. 합성을 사용하여 상속을 통해 정상적으로 수행 된 일부 작업을 수행 할 수 있습니다. – Kevin