在python中,如何让两个类共享一个方法的实现,该方法调用另一个方法以及每个类的特定实现

假设我有一个父类Parent,其抽象方法load在其子类中实现。现在,我有两个子类childA和childB,都继承自Parent。loadfor的实现childA和childB完全相同。但是 的此实现load调用另一个方法 ,get_paths该方法特定于childA和childB。父母是这样的:


from abc import ABC, abstractmethod

class Parent(ABC):

    def __init__(self, *params):

        # set up the params


    @abstractmethod

    def load(self, *params):

        # load files, according to each children


    def process(self, *params):

        # process the loaded files

然后是孩子们:


class childA(Parent):

    def __init__(self, *paramsP, *paramsA):

        super().__init__(*paramsP)

        # Set up the specific paramsA


    def get_paths(self, *params):

        # specific implementation to childA


    def load(self, *params):

        # Calls the self.get_paths method, identical to childB.load

class childB(Parent):

    def __init__(self, *paramsP, *paramsB):

        super().__init__(*paramsP)

        # Set up the specific paramsB


    def get_paths(self, *params):

        # specific implementation to childB


    def load(self, *params):

        # Calls the self.get_paths method, identical to childA.load

如何重用和load中的代码,但实现特定于每个类?我尝试了两种方法:childAchildBget_paths


(1) 继承childB自childA,并覆盖 的实现get_paths。在这种方法中,我有:


class childB(childA):

    def __init__(self, *paramsP, *paramsB):

        super().__init__(*paramsP)

        # Set up the specific paramsB


    def get_paths(self, *params):

        # specific implementation to childB

我把它称为:


b = childB(...)

b.load(...)



(2) Implement another class, `AB`, with the following definition:


```python

class AB(Parent):

    def __init__(self, *paramsP):

        super().__init__(*paramsP)


    @abstract method

    def get_paths(self, *params):

        # To be implemented in childA and childB


    def load(self, *params):

        # Implements the load from childA and childB

然后让childA和childB都继承自AB,并实现其特定的get_paths. 但是,这并没有那么有效,因为我收到错误:TypeError: Can't instantiate abstract class ChildB with abstract methods _AB__get_paths。


重要的是要添加我无法实现load,Parent因为还有其他类(childC、childD、 ...)具有独特的load实现。。我只想在childA和之间重用这段代码childB


那么,解决这个问题的正确方法是什么?


喵喵时光机
浏览 230回答 1
1回答

慕尼黑5688855

除非你想Parent用abstract继承.load,否则直接把实现放进去Parent。如果.load仅对这两个孩子来说很常见 - 您可以继承Parent第三个孩子,例如LoadMixin继承两者Parent并混合一种方法是:class LoadableChild(Parent):    def load(self, *params): ...class childA(LoadableChild):    def get_paths(self, *params): ...class childB(LoadableChild):    def get_paths(self, *params): ...另一个是:class LoadBase:    def load(self, *params): ...class childA(LoadBase, Parent):    def get_paths(self, *params): ...class childB(LoadBase, Parent):    def get_paths(self, *params): ...请注意后面方法中的继承顺序,如果您继承父类作为第一个超类,则没有简单的方法:如果你的 mixin 继承Parent– 没有明确的 MRO如果 mixin 继承object- 抽象上存在实例化错误.load。我想说,这是偏好问题,对我个人来说,第一种方法更干净
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python