我在实施以下要求时遇到了问题:
Interface
。ImplementationN
的n个类Interface
。UsingInterface
,使用Interface
中的函数来定义自己的函数。UsingInterface
中创建的函数,但实现UsingInteface
类之一的ImplementationN
方法所使用的函数。以下是我提出的解决方案:
答案 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