python - 将函数应用于继承的抽象方法中的所有函数
问题描述
我有一个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()
而不显式添加它?
任何帮助将不胜感激!
解决方案
我认为不建议自动分解您的方法的实现。所以我建议你自己分解它,这样可以更容易地执行诸如执行时间日志之类的事情。您可以这样做,而对代码的整体外观影响很小:
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,
])
推荐阅读
- dnssec - 如何启用 SSHFP?
- apache-kafka - Confluent Operator 添加额外的连接器
- javascript - 为什么 array.map 嵌套在 array.forEach 中(在这种情况下)比其他方式快得多?
- c++ - LLVM | 插入带有 uintptr_t 参数的钩子函数
- python - Python3 argp 对于从终端传递并在配置中传递的字符串的不同行为
- java - 允许保留阻止以解除对一种以上代理类型的阻止
- python - 在处理上述异常的过程中,发生了另一个异常错误发生
- ruby-on-rails - Rails 允许嵌套属性
- python - 在不带括号的 for 循环中使用 random.choices 从列表中打印出项目
- html - vw 和 vh 在谷歌浏览器上似乎无法正常工作