【问题标题】:Is it possible to detect which subclass a method is called from是否可以检测从哪个子类调用方法
【发布时间】:2021-12-04 07:32:36
【问题描述】:

我有一个继承到三个子类的超类。超类包含一个方法,其输出变量取决于调用该方法的子类。下面,您会看到一个示例,在该示例中,我为方法提供了一个参数来指示要生成的输出。

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') 

相反,我希望这个超类方法能够识别该方法是从哪个子类调用的。

我正在考虑类似的事情:

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') 

有没有办法做到这一点?

【问题讨论】:

  • 您是否需要sparsesvd 为其他目的返回这3 个值,或者您可以重写子类方法只是为了返回您在此上下文中需要的值?换句话说,你是在这里调用`sparsesvd方法还是在其他地方调用`sparsesvd方法

标签: python inheritance subclass super


【解决方案1】:

说实话,让超类的方法知道它是从哪个子类执行的,这听起来像是一种反模式。至少,这意味着每次添加子类时都必须调整超类。教科书的解决方案是将这些细节移到子类覆盖的方法中。例如:

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] 

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多