0

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?

MLguy
  • 1,776
  • 3
  • 15
  • 28
  • Not an answer to your question, but Python already has [Abstract Base Classes](https://docs.python.org/3/library/abc.html) for this purpose. You may find it simpler to use those then reinvent them. – Patrick Haugh Aug 06 '18 at 14:31
  • Possible duplicate of [python setattr for dynamic method creator with decorator](https://stackoverflow.com/questions/33134609/python-setattr-for-dynamic-method-creator-with-decorator) – MLguy Aug 07 '18 at 09:40
  • What are you not satisfied with in your first approach? –  Feb 20 '20 at 14:50
  • See the commented section with output of the code. The former approach does not correctly overloads 'cat' somehow. – MLguy Feb 20 '20 at 16:48

0 Answers0