假设我有一个父类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
那么,解决这个问题的正确方法是什么?
慕尼黑5688855
相关分类