How can we define a class decorator which allows us to overload the class constructor?

Viewed 29

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 in functools.singledispatch
  • the new class has a registerfriend method.
  • registerfriend takes a callable as input
  • registerfriend does something like klass.__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:

  1. a class named Apple.
  2. 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)
0 Answers
Related