Dynamically implement method by composition (like decorator in kotlin)
Solution 1:
I don't really understand why do you want to do it like that way. You can inherit your WrappingInterface
from the child class (Eg.: from Foo
):
Code:
class WrappingInterface(Foo):
def do_3(self):
super().do_3()
print("And then doing something else")
test = WrappingInterface()
test.do_1()
test.do_2()
test.do_3()
Output:
>>> python3 test.py
I am foo 1
I am foo 2
I am foo 3
And then doing something else
But if you really needed to extend the base classes then you can do it like this:
Dynamically extend base classes:
class WrappingInterface(SomeInterface):
def __init__(self, inf: SomeInterface):
self._inner = inf
def do_3(self):
self._inner.do_3()
print("And then doing something else")
WrappingInterface = type("WrappingInterface", (Foo,), dict(WrappingInterface.__dict__))
test = WrappingInterface(Foo())
test.do_1()
test.do_2()
test.do_3()
Output:
> python3 test.py
I am foo 1
I am foo 2
I am foo 3
And then doing something else
Or you can do everything inside your class (It's a little hacky but it works).
Code:
class WrappingInterface(SomeInterface):
def __init__(self, inf: SomeInterface):
self._inner = inf()
methods = [method for method in dir(inf) if not method.startswith('__')
and callable(getattr(inf, method))]
for method in methods:
if method in self.__class__.__dict__:
continue
setattr(WrappingInterface, method, getattr(inf, method))
def do_3(self):
self._inner.do_3()
print("And then doing something else")
test = WrappingInterface(Foo)
test.do_1()
test.do_2()
test.do_3()
Output:
>>> python3 test.py
I am foo 1
I am foo 2
I am foo 3
And then doing something else
Note:
I recommend to check the Abstract Base Classes
in Python to do a "real" Abstraction. Reference: https://docs.python.org/3/library/abc.html