![](/img/trans.png)
[英]Can you create a list of class objects and use class functions that way?
[英]Create class and prep data once that all objects can then use
請原諒我的術語,我還在學習 Python 和 OOP。
我有 2 個 py 文件:
數據.py
主程序
在 main.py 中,我想使用類似以下內容創建 n 個對象:
USD_ON_SOFR = rate_interp('USD', 'ON', 'SOFR', '2023-01-26')
以上適用於美元,但也可能適用於 n 種其他貨幣和不同的利率曲線——可能有 15-20 個單獨的對象。
目標是使用(例如)返回一個插值:
ans = USD_ON_SOFR.interp(45)
這里的想法是 data.py 負責創建對象。 我希望它從 SQL 數據庫中提取一次數據,例如:
prices_df = pd.read_sql('select * from rates_prices', db_conn)
然后我希望每個 object 使用初始數據 [prices_df] 而無需重新查詢 SQL 數據庫。 我知道如何根據需要將每個 object 切片 df。
我的問題是,如何設置 class 以在第一次創建 object 時最初提取該數據一次,並在每次創建不同的 object 時將其提供給每個 object?
這是我嘗試過的一些代碼,我曾想過使用__new__
:
在數據.py中:
class rate_interp():
def __new__(cls, *args, **kwargs):
db_conn = db.connect(r'C:\Users\user\DataGripProjects\default\identifier.sqlite')
prices = pd.read_sql('select * from rates_prices', db_conn)
def __init__(self,cls,ccy,type1,type2,pricing_date):
self.curve_ID = ccy + '_' + type1 + '_' + type2
self.pricing_date = pricing_date
self.df_cut = cls.new_query.loc[cls.new_query['curve_family']==type2+type1+ccy+pricing_date]
self.interp = interpolate.interp1d(self.df_cut['days'],self.df_cut['LAST_PRICE'])`
在 main.py 中:
USD_ON_SOFR = rate_interp('USD', 'ON', 'SOFR', '2023-01-26')
ans = USD_ON_SOFR.interp(45).item() #45 is just an example
錯誤:
ans = USD_ON_SOFR.interp(45).item()
AttributeError: 'NoneType' object has no attribute 'interp'
你可以做一個緩存的 function 讓你的數據庫調用data.py
import functools
import pandas as pd
@functools.cache
def get_data_from_db():
db_conn = db.connect(r'C:\Users\user\DataGripProjects\default\identifier.sqlite')
return pd.read_sql('select * from rates_prices', db_conn)
這樣它只會在您第一次調用 function 時調用數據庫; 后續調用不會。 然后你可以在你的構造函數中調用它:
class rate_interp:
def __init__(*args, **kwargs):
price_data = get_data_from_db()
...
您可以將數據存儲在 class 變量中:
class Demo:
data = None
def __init__(self, a, b):
if Demo.data is None:
print('one time init')
Demo.data = [1,2,3]
self.a, self.b = a, b
def __repr__(self):
return f'Demo(data={self.data}, a={self.a}, b={self.b})'
print(Demo(1,2))
print(Demo(3,4))
print(Demo(5,6))
Output:
one time init
Demo(data=[1, 2, 3], a=1, b=2)
Demo(data=[1, 2, 3], a=3, b=4)
Demo(data=[1, 2, 3], a=5, b=6)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.