我有一個需要引用大型數據集的python類。我需要創建數千個類的實例,所以我不想每次都加載數據集。這將是簡單的把數據在必須首先創建並傳遞到另一個作爲參數另一個類:Python-加載第一類實例的數據
class Dataset():
def __init__(self, filename):
# load dataset...
class Class_using_dataset():
def __init__(self, ds)
# use the dataset and do other stuff
ds = Dataset('file.csv')
c1 = Class_using_dataset(ds)
c2 = Class_using_dataset(ds)
# etc...
但我不希望我的用戶不得不處理的數據集,因爲如果我可以在後臺執行它,它總是一樣的。
當我創建我的類的第一個實例時,是否有將數據加載到全局名稱空間中的pythonic/canonical方法?我希望如下:
class Class_using_dataset():
def __init__(self):
if dataset doesn't exist:
load dataset into global namespace
use dataset
不要。使用'Class_using_dataset'作爲數據集的一種方法,或者採用一個數據集的'Class'的類方法。在任何一種情況下,您都可以採取封閉或限制的方法來消除成本,同時保持局部地理位置。全局變量很糟糕。 – Veedrac