在python中扩展类

2024-09-22 14:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

比如说,我有一些MainClass,在它的方法中的某个点上,OtherClass的对象的实例化作为MainClass的属性。你知道吗

mainobj = MainClass()
isinstance(mainobj.otherclassobj, OtherClass) == True

现在,我想扩展OtherClass,然后将MainClass与新的扩展类一起使用。你知道吗

除了扩展MainClass和重新定义所有实例化self.otherclassobj的方法以从ExtendedOtherClass开始之外,我还有更方便的选择吗?你知道吗


Tags: 对象实例方法selftrue属性定义isinstance
2条回答

如果可以稍微更改MainClass的实现,则不需要从中继承。就吃点像

class MainClass:
    def __init__(self, ..., otherclass=OtherClass):
        self.otherclassobj = otherclass()
        ...
    ...

默认情况下,MainClass将使用OtherClass,但您可以将ExtendedOtherClass作为关键字参数传入。你知道吗

如果您已经不需要OtherClass,那么可以执行以下操作

from other_class_module import ExtendedOtherClass as OtherClass

如果两个类都需要,或者逻辑/方法都需要更改,则需要重新实现/扩展MainClass。你知道吗

相关问题 更多 >