我有一個名為Insights的超類,它有一個抽象的方法calculate_insights()。
幾個子類繼承,其中的BrandInsights(Insights)類。
在這些子類中,函式calculate_insights()呼叫了其他幾個函式。我想要的是為這些其他函式提供一個定時記錄器,而不需要總是顯式地添加記錄器(因為這將大大降低可讀性)
我的代碼現在看起來是這樣。
我的代碼現在看起來是這樣的:
from abc import ABC, abstractmethod
class Insights(ABC)。
def __init__(self):
self.bq = BigQueryLayer()
self.db = DatabaseLayer()
def calculate_insights(self)。
# here should go something to time all functions called in calculate_insights.
通過。
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()中的每個函式執行前后都有一個時間被記錄下來,而不需要明確添加它?
如果能得到任何幫助,我們將不勝感激!
uj5u.com熱心網友回復:
我認為自動拆分你的方法的實作是不可取的。所以我建議你自己把它拆開,這將使你更容易執行諸如執行時間記錄的事情。你可以在對代碼的整體外觀影響不大的情況下做到這一點:
。class Insights(ABC)。
def timed_execution(self, callbacks)。
for callback in callbacks:
start_time = time.time()
回呼()
end_time = time.time()
print(f'{callback. __name__}花了{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,
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/320088.html
標籤:
