我希望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'
答案 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)