我如何 运行 在 python class 中收集相似的方法?

How do I run a collection of similar methods in a python class?

我正在处理大型 Python class,其中包含数十种“业务逻辑”方法和一些辅助方法。最后有一些有趣的代码用于 运行 所有“calc_metric_*”方法。

有点像:

class CalculateMetrics:
    ...

    def calc_metric_x1(self):
        ...

    def calc_metric_x2(self):
        ...

    def calc_metric_x3(self):
        ...

    def calc_metric_x4(self):
        ...
    
    ...

    def calc_metric_x50(self):
        ...

    def run_all(self):
       method_list = [m for m in dir(self) 
                      if callable(getattr(self, m)) 
                      and m.startswith('calc_metric_')]

       for m in method_list:
           # Call each method
           getattr(self, m)()

使用 getattr + 引用方法名称对我来说似乎不是最佳选择。在 Python 中是否有更好的方法来实现此目的?

您可以使用像这样收集它们的装饰函数:

def calc_metric(func):
    if func not in calc_metric.calc_metric_funcs:
        calc_metric.calc_metric_funcs.append(func)
    return func


calc_metric.calc_metric_funcs = []

然后你需要用@calc_metric:

装饰所有需要的功能
    @calc_metric
    def calc_metric_x1(self):
        
        ...

    @calc_metric
    def calc_metric_x2(self):
        ...

    ...

    @calc_metric
    def calc_metric_x50(self):
        ...

你的 run_all() 函数将是这样的:

    def run_all(self):
        for f in calc_metric.calc_metric_funcs:
            f(self)

请注意,calc_metric 函数必须在 CalculateMetrics class 之外声明。