定义接口并使用接口的多个实现

时间:2017-02-20 14:26:24

标签: python inheritance interface multiple-inheritance

我在实施以下要求时遇到了问题:

  1. 创建一个接口类Interface
  2. 创建以不同方式实现ImplementationN的n个类Interface
  3. 创建一个新类UsingInterface,使用Interface中的函数来定义自己的函数。
  4. 创建n个新类,允许使用UsingInterface中创建的函数,但实现UsingInteface类之一的ImplementationN方法所使用的函数。
  5. 以下是我提出的解决方案:

1 个答案:

答案 0 :(得分: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