Let say that we want to implement a class interface overloading all public methods with the same logic. Therefore, rather than manually defining all methods and copy-pasting the logic across all implemented methods, one might want to abstract the process as follows:
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)>
A solution might be to replace __init__
with the following, but then the logic would not be fully abstracted.
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
Question: How to iterate while overriding all public methods of Interface
during the initialisation of Implementation
?