vendredi 3 mars 2023

Why use a superclass's __init__ to change it into a subclass?

I'm working on replicating the SHAP package algorithm - an explainability algorithm for machine learning. I've been reading through the author's code, and I've come across a pattern I've never seen before.

The author has created a superclass called Explainer, which is a common interface for all the different model specific implementations of the algorithm. The Explainer's __init__ method accepts a string for the algorithm type and switches itself to the corresponding subclass if called directly. It does this using multiple versions of the following pattern:

if algorithm == "exact":
    self.__class__ = explainers.Exact
    explainers.Exact.__init__(self, self.model, self.masker, link=self.link, feature_names=self.feature_names, linearize_link=linearize_link, **kwargs)

I understand that this code sets the superclass to one of its subclasses and initialises the subclass by passing itself to __init__. But why would you do this?

Aucun commentaire:

Enregistrer un commentaire