Home > other >  Is it possible to detect which subclass a method is called from
Is it possible to detect which subclass a method is called from

Time:10-16

I have a superclass with inheritance to three subclasses. The superclass contains a method whose output variable depends on the subclass that calls the method. Below, you see an example in which I feed the method a parameter to indicate what output to generate.

def dimensionality_reduction(self, algorithm, sparse_weighted_matrix, factors):
    ut, _, v = sparsesvd(sparse_weighted_matrix, factors)
    if algorithm == 'a':
        return ut
    elif algorithm = 'b':
        return v
    else:
        raise Exception('Invalid algorithm selected') 

Instead, I would like this superclass method to recognize from which subclass the method is called.

I am thinking about something like:

def dimensionality_reduction(self, sparse_weighted_matrix, factors):
    ut, _, v = sparsesvd(sparse_weighted_matrix, factors)
    if subclass == 'method_a':
        return ut
    elif subclass = 'method_b':
        return v
    else:
        raise Exception('Invalid algorithm selected') 

Is there some way to do this?

CodePudding user response:

To be honest, having the superclass' method know what subclass it's executed from sounds like an anti pattern. At the very least, this would mean you'll have to adjust the superclass every time you add a subclass. The textbook solution would be to move these details to a method the subclasses override. E.g.:

class Superclass:
    def handle_sparsesvd_result(self, result):
        # Must be overridden by subclasses
        raise Exception('Invalid algorithm selected') 

    def dimensionality_reduction(self, algorithm, sparse_weighted_matrix, factors):
        result = sparsesvd(sparse_weighted_matrix, factors)
        return self.handle_sparsesvd_result(result)

class SubClassA(SuperClass):
    def handle_sparsesvd_result(self, result):
        return result[0] 

class SubClassB(SuperClass):
    def handle_sparsesvd_result(self, result):
        return result[2] 

  • Related