将函数应用于继承的抽象方法中的所有函数

Apply function to all functions in inherited abstractmethod

我有一个名为 Insights 的超级class,它有一个抽象方法 calculate_insights()

几个子class继承,其中class BrandInsights(Insights) 在 subclasses 中,函数 calculate_insights() 调用了其他几个函数。我想要的是为那些其他功能提供一个计时记录器,而不总是显式添加记录器(因为这会大大降低可读性)

我的代码现在看起来像这样:

from abc import ABC, abstractmethod

class Insights(ABC):

    def __init__(self):
        self.bq = BigQueryLayer()
        self.db = DatabaseLayer()

    @abstractmethod
    def calculate_insights(self):
        # here should go something to time all functions called in calculate_insights
        pass

class BrandInsights(Insights):
    
    def calculate_insights():
        self.db.extend_customer_loyalty()
        self.db.extend_brand_combiners()
        self.db.extend_brand_recency()
        ...

class StoreInsights(Insights):

    def calculate_insights():
        self.db.extend_competition_view()
        self.db.extend_busiest_hours()
        ...

如何确保在 calculate_insights() 中的每个函数执行之前和之后记录时间而不明确添加它?

如有任何帮助,我们将不胜感激!

我认为自动分解方法的实现是不可取的。所以我建议你自己分解它,这样可以更容易地执行诸如执行时间记录之类的事情。您可以做到这一点,而对代码的整体外观影响很小:

class Insights(ABC):

    def timed_execution(self, callbacks):
        for callback in callbacks:
            start_time = time.time()
            callback()
            end_time = time.time()
            print(f'{callback.__name__} took {end_time-start_time:.3f}s')


class BrandInsights(Insights):
    
    def calculate_insights():
        super().timed_execution([
            self.db.extend_customer_loyalty,
            self.db.extend_brand_combiners,
            self.db.extend_brand_recency,
        ])