假设我有一个父类Parent
,其抽象方法load
在其子类中实现。现在,我有两个子类childA
和childB
,它们都继承自Parent
。对于{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):
# loads 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
如何在childA
和childB
中重用来自load
的代码,但是get_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(...)
However, when I call `childB.load`, the `get_paths` called inside of it is `childA.get_paths`. I noticed that because I was getting an error when running `b.load`, so tried putting a break point with `ipdb` inside of `childB.get_paths`, but execution did not stop. But when I put the breaking point inside of `childA.get_paths`, it did break.
(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
重要的是添加I无法在Parent
中实现load
,因为还有其他类(childC
,childD
,…)具有唯一的load
实现。。我只想在childA
和childB
之间重用这段代码
那么,解决这个问题的正确方法是什么
除非您希望
Parent
与抽象.load
一起继承,否则只需将实现放入Parent
如果
.load
只对这两个孩子通用,那么您可以从Parent
继承第三个类似LoadMixin
的孩子,并继承Parent
和mixin一种办法是:
另一个是:
请注意在后面的方法中的继承顺序,如果将父类作为第一个超类继承,则没有简单的方法:
Parent
,那么就没有明确的MROobject
–抽象.load
上有实例化错误李>这是我个人偏好的问题,我会说,对我个人来说,第一种方法更干净
相关问题 更多 >
编程相关推荐