And*_*obb 6 python inheritance python-3.x
我是 Python 新手,我正在尝试实现我在 C# 中经常使用的结构。我需要读入并处理来自一堆不同表的数据。每个表都有少量代码需要不同,但大多数都可以重用。因此,我尝试创建一个抽象基类来处理大部分处理,并调用抽象方法来进行特定于表的处理。然后,我创建为每个表实现这些函数的类的具体实现。不幸的是,基类中的共享方法正在调用抽象方法,而不是子类中实现的方法。
这是抽象类的精简版本。
from abc import ABC, abstractmethod, ABCMeta
class AbstractDataResampler(object):
__metaclass__ = ABCMeta
def __init__(self, database):
self.client = database
self.__configure_database()
def __resample_data(self):
raise NotImplementedError()
def get_resampled_data(self):
return __resample_data()
Run Code Online (Sandbox Code Playgroud)
这是具体实现的精简版本。
from DataProcessors.AbstractDataResampler import AbstractDataResampler as Parent
class SpecificDataResampler(Parent)
def __init__(self, database):
super().__init__(database)
def __resample_data(self):
... implementation
Run Code Online (Sandbox Code Playgroud)
当我创建 SpecificDataResampler 的实例并调用 get_resampled_data() 时,我收到 NotImplementedException,因为正在调用 __resample_data 的基本版本,而不是实现的子版本。
resampler = SpecificDataResampler(db)
resampler.get_resampled_data()
Run Code Online (Sandbox Code Playgroud)
是否有可能完成我在 Python 3 中尝试做的事情?即子类调用抽象基类中实现的方法,然后使用子类重写的方法?
如果这是重复的,或者工作中存在一个简单的错误,我深表歉意。我在网上尝试了很多建议,但没有一个有效(我认为很多都是针对 Python 2.7 的)。
注意:这是事情的简化版本。SpecificDataResampler 实际上是一个单例,遵循这种模式,因此 SpecificDataResampler 实际上是一个嵌套内部类。然而,我在没有使用单例模式的情况下对此进行了测试,并收到了相同的错误。
| 归档时间: |
|
| 查看次数: |
1453 次 |
| 最近记录: |