2016-07-07 35 views
1

我有一個需要引用大型數據集的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 
+0

不要。使用'Class_using_dataset'作爲數據集的一種方法,或者採用一個數據集的'Class'的類方法。在任何一種情況下,您都可以採取封閉或限制的方法來消除成本,同時保持局部地理位置。全局變量很糟糕。 – Veedrac

回答

1

您可以數據集加載到類變量在Class_using_dataset類被解析的時間,或當用戶創建的類的第一個實例。

第一種策略只需要您將加載數據集的行移動到類本身中。

class Dataset(): 
    def __init__(self, filename): 
     # load dataset... 

class Class_using_dataset(): 
    ds = Dataset('file.csv') 

    def __init__(self) 
     # use the dataset and do other stuff 

# `Class_using_dataset.ds` already has the loaded dataset 
c1 = Class_using_dataset() 
c2 = Class_using_dataset() 

對於第二個,分配給None類變量,而如果是dsNone加載該數據集在__init__方法。

class Dataset(): 
    def __init__(self, filename): 
     # load dataset... 

class Class_using_dataset(): 
    ds = None 

    def __init__(self) 
     if Class_using_dataset.ds is None: 
      Class_using_dataset.ds = Dataset('file.csv') 
     # use the dataset and do other stuff 

# `Class_using_dataset.ds` is `None` 
c1 = Class_using_dataset() 
# Now the dataset is loaded 
c2 = Class_using_dataset() 
1

如果數據集在類的所有實例之間共享,請將其設爲類變量。

class Dataset(): 
    def __init__(self, filename): 
     # load dataset... 

class Class_using_dataset(): 
    def __init__(self) 
     # use the dataset and do other stuff 

Class_using_dataset.ds = Dataset('file.csv') 
c1 = Class_using_dataset() 
c2 = Class_using_dataset() 
# etc... 
+0

是否有可能做一個變化,用戶根本不必看到它?在你的版本中,它看起來像只是在你明確設置它的行加載文件。如果我將它加載到類中,每次創建實例或僅創建一次時會加載它嗎? – ericksonla

+0

如果你把它放在類中,__fore__在__init__中,它只會加載一次。試一試(在'Dataset'類中使用一個簡單的'print()')並參見。 – TigerhawkT3

相關問題