在 python 中将瘦派生类添加到库基类

问题描述 投票:0回答:0

我尝试为派生类实现一个克隆函数,使用基类的克隆方法。但我遗漏了一些东西,否则这就不是 Python。

我正在使用 vpython 库。 vpython.compound 类很复杂,我想添加一些功能。所以我做了这样的事情:

class MyCompound(compound):
    myextra = 0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.myextra = 1

我认为这会让 MyCompound 在我使用它的任何地方看起来都像一个化合物。所以现在它是化合物的直接替代品,而且我可以操纵额外的数据。

但是,我需要实现特殊的克隆方法 compound.clone()(这是一种工厂方法,它不仅仅是某种深度复制。)

想要写这样的东西(在MyCompound内)(“”引号中的位是不合法的)

    def clone(self) -> MyCompound:
        mc = "a new but uninitialised MyCompound object"
        "mc.compound" = super().clone()
        mc.myextra = self.myextra + 1
        return mc

如有必要,我可以让 MyCompound 构造函数更聪明,但我仍然遗漏了一些东西。

class MyCompound(compound):
    myextra = 0
    def __init__(self, *args, **kwargs):
        if len(*args) and type(args[0]) == compound:
            "super() = super().clone()"
        else:
            super().__init__(*args, **kwargs)
            self.myextra = 1

也许我想在这里用 python 编写 C++。是否可以分配给“基类对象” 派生类的?什么是 pythonic 方式?

python oop inheritance clone wrapper
© www.soinside.com 2019 - 2024. All rights reserved.