How can we write a class-decorator which accepts the old class as input and outputs a new class such that:
- the old class
__init__is wrapped infunctools.singledispatch - the new class has a
registerfriendmethod. registerfriendtakes a callable as inputregisterfrienddoes something likeklass.__init__.register(callable)
Assume that __init__ always takes exactly one argument besides self
We might want to overload __new__ instead of __init__ or overload the __call__ in the meta-class.
A use case occurs when we have two classes:
- a class named
Apple. - a class named
Orange.
The Apple class was written with no idea what an Orange was.
At some later date, we decide to over-load the Apple class constructor so that we can construct an an Apple from an Orange
def new_constructor(orn:Orange):
pass
Apple.registerfriend(new_constructor)
orng = Orange(None) # meta(Orange).__call__ is registered for type(None)
appul = Apple(org)