让我们说我们要实现一个类接口,以相同的逻辑重载所有公共方法。因此,与其手动定义所有方法并在所有实现的方法之间复制粘贴逻辑,不如将过程抽象如下:
class Interface:
def cat(self, i):
"""Implement."""
def dog(self, i, j=2):
"""Implement."""
class Implementation(Interface):
def __init__(self):
for method in [method for method in vars(Interface) if '__' not in method]:
setattr(self, method, lambda *a, **k: self.overload(method, *a, **k))
def overload(self, method, *a, **k):
print('Calling method {}'.format(method))
return getattr(Interface, method)(self, *a, **k)
implementation = Implementation()
implementation.dog(1)
implementation.cat(1)
implementation.cat
implementation.dog
# Console:
# Calling method dog
# Calling method dog
# <function __main__.Implementation.__init__.<locals>.<lambda>(*a, **k)>
# <function __main__.Implementation.__init__.<locals>.<lambda>(*a, **k)>
一种解决方案可能是将__init__
替换为以下内容,但随后的逻辑将无法完全抽象。
class Implementation(Interface):
def __init__(self):
setattr(self, 'cat', lambda *a, **k: self.overload('cat', *a, **k))
setattr(self, 'dog', lambda *a, **k: self.overload('dog', *a, **k))
def overload(self, method, *a, **k):
print('Calling method {}'.format(method))
return getattr(Interface, method)(self, *a, **k)
implementation = Implementation()
implementation.dog(1)
implementation.cat(1)
# Console.
# Calling method dog
# Calling method cat
问题:如何在初始化Interface
的过程中重写Implementation
的所有公共方法?