我目前正在重構了一些代碼,利用全局的成類:使用方法返回值或將方法結果分配給屬性?
import pandas as pd
from datetime import date, timedelta
class test(object):
def __init__(self):
self.fiscal_cal = pd.read_csv(r'c:\CENSORED')
self.today = date.today().strftime("%Y-%m-%d")
self.yesterday = (date.today() - timedelta(1)).strftime("%Y-%m-%d")
def _calc_period_start(self,input_date,period):
month, year, season = map(lambda x: self.fiscal_cal[x][self.fiscal_cal['date']==input_date], ['fmth','fyr','fiscal_season'])
if period == 'month':
return self.fiscal_cal['date'][(self.fiscal_cal['fmth'] == int(month)) & (self.fiscal_cal['fyr'] == int(year))].irow(0)
return self.fiscal_cal['date'][self.fiscal_cal['fiscal_season'] == season.values[0]].irow(0)
def _calc_match_date(self,input_date,years_back=1):
fwk, fyr, fdt = map(lambda x: self.fiscal_cal[x][self.fiscal_cal['date']==input_date], ['fwk','fyr','fdt'])
_ = self.fiscal_cal['date'][(self.fiscal_cal['fdt'] == int(fdt)) & (self.fiscal_cal['fyr'] == int(fyr - years_back))]
return _.item()
def month_start_ty(self):
return self._calc_period_start(self.today,period='month')
def season_start_ty(self):
return self._calc_period_start(self.today,period = 'season')
def match_ly(self):
_ = self._calc_match_date(self.today,1)
return _
def month_start_ly(self):
_ = self._calc_match_date(self.today,1)
return self._calc_period_start(_,period = "month")
def season_start_ly(self):
_ = self._calc_match_date(self.today,1)
return self._calc_period_start(_,period = 'season')
我在哪裏,我應該使用的方法將信息返回到我的節目混淆 - 或分配方法的輸出到一個屬性,然後訪問/使用屬性
import pandas as pd
from datetime import date, timedelta
class test(object):
def __init__(self):
self.fiscal_cal = pd.read_csv(r'c:\CENSORED')
self.today = date.today().strftime("%Y-%m-%d")
self.yesterday = (date.today() - timedelta(1)).strftime("%Y-%m-%d")
self.month_start_ty = self._calc_period_start(self.today,period='month')
def _calc_period_start(self,input_date,period):
month, year, season = map(lambda x: self.fiscal_cal[x][self.fiscal_cal['date']==input_date], ['fmth','fyr','fiscal_season'])
if period == 'month':
return self.fiscal_cal['date'][(self.fiscal_cal['fmth'] == int(month)) & (self.fiscal_cal['fyr'] == int(year))].irow(0)
return self.fiscal_cal['date'][self.fiscal_cal['fiscal_season'] == season.values[0]].irow(0)
def _calc_match_date(self,input_date,years_back=1):
fwk, fyr, fdt = map(lambda x: self.fiscal_cal[x][self.fiscal_cal['date']==input_date], ['fwk','fyr','fdt'])
_ = self.fiscal_cal['date'][(self.fiscal_cal['fdt'] == int(fdt)) & (self.fiscal_cal['fyr'] == int(fyr - years_back))]
return _.item()
這些日期被作爲參數傳遞給其他API調用函數。
我不確定我是否理解這個問題。你是否想知道當你創建一個實例或者只是公開執行計算的方法時,你應該在你的類中計算屬性?我認爲答案將取決於需要多久的價值(以及計算成本)。中間層可能是在第一次請求時計算該值,然後將其緩存以供後續請求使用。 – Blckknght
我想弄清楚返回計算值的約定是否應該是test.a(),或者是否應該將計算值分配給要通過test.a調用的屬性。如果將一個計算值分配給一個屬性是慣用的,那麼這樣做的pythonic方法是什麼? – user2726995