【问题标题】:Defining an interface and using multiple implemenations of the interface定义接口并使用接口的多个实现
【发布时间】:2017-07-09 21:10:48
【问题描述】:

我无法理解以下要求的实现:

  1. 创建一个接口类Interface
  2. 创建 n 个类 ImplementationN,以不同方式实现 Interface
  3. 创建一个新类 UsingInterface,它使用来自 Interface 的函数来定义自己的函数。
  4. 创建 n 个新类,允许使用在 UsingInterface 中创建的函数,但通过 ImplementationN 类之一实现 UsingInteface 的方法使用的函数。

以下是我想出的解决方案:

【问题讨论】:

  • 你不明白什么?这是Strategy Pattern
  • 我不确定如何在 Python 中实现此行为,但认为我已经在下面的示例中正确地做到了。感谢您提供反馈。
  • 也许可以在Code Review 上发帖。

标签: python inheritance interface multiple-inheritance


【解决方案1】:

在线解释。解决方案中的一个关键是将UsingInterface 设置为metaclass=ABCMeta,因此它(在本例中为IDE)不需要实现func1

from abc import ABCMeta, abstractmethod


class Interface(object, metaclass=ABCMeta):
    """Class that defines an interface."""
    @abstractmethod
    def func1(self):
        pass


class Implementation1(Interface):
    """Class that implements the interface one way."""
    def func1(self):
        print('func1 was implemented here')


class Implementation2(Interface):
    """Class that implements the interface another way, differently."""
    def func1(self):
        print('func1 was implemented here as well, but differently')


class UsingInterface(Interface,  metaclass=ABCMeta):
    """Class that uses the interface to implement its own functions.
    `func1` is not implemented here, hence this has to be an `ABCMeta` class.
    Later, the correct implementation of `func1` based on the inherited
    Implementation class shall be used.

    We're inheriting `Interface`, so the IDE can tell us which methods
    we can call (in this case `self.func1()`).
    """
    def func2(self):
        print("I'm running func1 from the Interface: ")
        self.func1()


class Usage1(UsingInterface, Implementation1):
    pass    


class Usage2(UsingInterface, Implementation2):
    pass

u1 = Usage1()
u1.func2()
# I'm running func1 from the Interface:
# func1 was implemented here

u2 = Usage2()
u2.func2()
# I'm running func1 from the Interface:
# func1 was implemented here as well, but differently

【讨论】:

    猜你喜欢
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    相关资源
    最近更新 更多