我有很多从一个基类继承的不同子类。然而,所有不同的子类都实现了非常相似的方法。因此,如果我想更改子类中的代码,我必须多次更改。
对我来说,这听起来像是不好的做法,我想正确地实施它。但是经过大量的谷歌搜索后,我仍然没有找到一种连贯的方式来说明如何做到这一点。
这是我的意思的一个例子:
from ABC import ABC, abstractmethod
import logging.config
class BaseModel(ABC):
def __init__(self):
# initialize logging
logging.config.fileConfig(os.path.join(os.getcwd(),
'../myconfig.ini'))
self.logger = logging.getLogger(__name__)
@abstractmethod
def prepare_data(self):
"""
Prepares the needed data.
"""
self.logger.info('Data preparation started.\n')
pass
所以这是我的BaseClass。现在从这个类中,多个其他类继承了init和 prepare_data 方法。每个类的 prepare_data 方法都非常相似。
class Class_One(BaseModel):
def __init__(self):
super.__init()__
def prepare_data(self):
super().prepare_data()
# Some code that this method does
class Class_Two(BaseModel):
def __init__(self):
super.__init()__
def prepare_data(self):
super().prepare_data()
# Some code that this method does
# Code is almost the same as for Class_One
class Class_Three(BaseModel):
def __init__(self):
super.__init()__
def prepare_data(self):
super().prepare_data()
# Some code that this method does
# Code is almost the same as for Class_One and Class_Two
# etc.
我想您可以将这些方法重构到另一个文件中,然后在每个类中调用它们。我很想知道如何正确地做到这一点。提前非常感谢!
qq_遁去的一_1
相关分类