mercredi 13 avril 2016

Add validation to __call__ methods in Python

I have a large hierarchy of classes stemming from Function class (for example SineFunction would be a child), and all of them implement the __call__ method, as well as other methods (for example derivation or more specialized numerical methods).

What is the cleanest way of adding common logic to each of these __call__ methods based on the type of the input? Formally, I'd like to have something like

def __call__(self,x):
    if isinstance(x,Distribution):
        return FunctionDistribution(x,self)
    else:
        # Go back to previous logic

for each child class of Function. I could add super() at each implementation of __call__ but that would be painful. Anything easier to achieve this?

Aucun commentaire:

Enregistrer un commentaire