如何让部分抽象的父类调用子类中方法的具体版本?

问题描述 投票:0回答:0

我有一些代码需要在某些硬件上运行以调用仅存在于该硬件上的库和驱动程序模块。但我想在无法加载这些库/驱动程序的单独机器上开发。

我的解决方案是实现一个父类,它抽象出使用这些特定于硬件的库的方法。然后在运行代码时,一个配置变量将决定是实例化真实的还是模拟的孩子。

代码看起来像这样

abstract_parent.py

from abc import ABC, abstractmethod

class FooClass:
  <all concrete members and methods>

class PartiallAbstractParent(ABC):
  def partiallyAbstractMethod(foo_list:list):
    <DO STUFF COMMON TO ALL CHILDREN>
    for foo in foo_list:
      fullyAbstractMethodOne(foo)
    
    fullyAbstractMethodTwo() 

  @abstractmethod
  fullyAbstractMethodOne(FooClass:foo_element)

  @abstractmethod
  fullyAbstractMethodTwo()

real_child.py

from abstract_parent import PartiallAbstractParent, FooClass
from real_hardware_libraries import realHardwareMethodOne()

class RealChild(PartiallAbstractParent):
  fullyAbstractMethodOne(FooClass:foo_element):
    realHardwareMethod()

  fullyAbstractMethodTwo():
    realHardwareMethod()

mock_child.py

from abstract_parent import PartiallAbstractParent, FooClass

class FakeChild(PartiallAbstractParent):
  fullyAbstractMethodOne(FooClass:foo_element):
    <DO FAKE STUFF HERE>

  fullyAbstractMethodTwo():
    <DO FAKE STUFF HERE>

因此,如果设置了配置

REAL_HARDWARE
main.py
将导入
real_child.py
并实例化,否则它将导入
mock_child.py
并实例化它。

我不确定如何在 python 中“正确地”执行此操作,我如何让父类代码执行但将部分抽象函数中的所有调用替换为子类具体定义的方法。

如果我使用子类调用

child_instance.partiallyAbstractMethod(foo_list)
它会自动调用在它自己的类中定义的具体方法吗?

其次,有没有更好的方法来嘲笑孩子?我查看了模拟模块,但不清楚我如何创建一个模拟来代替真实的类,而不是导入 hardware_library,并只覆盖某些方法。

python mocking abstract-class
© www.soinside.com 2019 - 2024. All rights reserved.