Explaination в режиме реального времени. Одним из ключей решения было установить 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
Что вам не нравится? Это [шаблон стратегии] (https://en.wikipedia.org/wiki/Strategy_pattern). –
Я не был уверен, как реализовать это поведение в Python, но думаю, что мне удалось сделать это правильно в приведенном ниже примере. Обратная связь приветствуется. – user1211030
Возможно, сообщение на [codereview.se]. –