当父 class 不能将其自身作为构造函数的参数时,使用实例初始化扩展 class

Initializing an extended class with an instance when the parent class can't take itself as argument for the constructor

好的。我正在尝试通过创建子 class 来扩展数据结构 class。用例是程序将已经有父 class 的实例并将其传递给子 class 的构造函数。换句话说,我有一个父 class、A 的实例,我想将它提供给扩展 class 构造函数以获得扩展 class、B 的实例。

class child(Parent):
    def __init__ (self, dataInstance=None):
        super(child, self).__init__(dataInstance)

child.someparentmethod() # YES! 

因此,如果 Parent class 可以在其构造函数中获取其自身的实例,这将起作用(实际上我正在处理多个 classes,其中有些可以,有些则不能)。我想避免的 hack-y 只是将父数据结构作为另一个 class 的 属性 传递:

class notChild():
    def __init__ (self, dataInstance=None):
        self.data = dataInstance

notChild.data.someparentmethod()  # yuck.

我在 python 中对 OOP 比较陌生,我希望我忽略了一些明显的东西。谢谢!

好的。这是我使用的解决方案,它特定于实现,我很想听听是否有更多 general/pythonic 方法来做到这一点:

class child(pandas.Panel4D):
    def __init__ (self, d=None):
        if isinstance(d, pandas.Panel4D):
            d = d._data
            super(child, self).__init__(d)
        else:
            super(child, self).__init__(d)

本质上,如果子构造函数被提供给父实例,它会访问它的基础数据,即父构造函数可以摄取的class。