首页 > 解决方案 > 将函数应用于继承的抽象方法中的所有函数

问题描述

我有一个Insights用 abstractmethod调用的超类calculate_insights()

几个子类继承,其中类BrandInsights(Insights) 在子类中,函数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()而不显式添加它?

任何帮助将不胜感激!

标签: pythonpython-3.xinheritancesuperclass

解决方案


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

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,
        ])

推荐阅读