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



我有一个超类Insights,它有一个抽象方法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()中执行每个函数之前和之后记录时间而不显式添加它?

任何帮助都将非常感激!

我认为自动分解你的方法的实现是不明智的。所以我建议你自己把它分解,这将使执行时间日志之类的事情变得更容易。这样做只会对代码的整体外观产生很小的影响:

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

最新更新