继承和对象副本

2024-09-27 09:26:07 发布

您现在位置: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'

Tags: 对象selfbasethatinitdefthisclass
1条回答
网友
1楼 · 发布于 2024-09-27 09:26:07

这似乎不是“inherit”的问题,您只想合并来自另一个对象的数据

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)

相关问题 更多 >

    热门问题