2016-07-07 7 views
1

큰 데이터 세트를 참조해야하는 파이썬 클래스가 있습니다. 매번 데이터 세트를로드하고 싶지 않기 때문에 클래스 인스턴스를 수천 개 생성해야합니다. 처음 생성 및 인수로 다른 하나에 전달되어야하는 다른 클래스에 데이터를 넣어 간단 될 것이다 :파이썬 - 클래스의 첫 번째 인스턴스에 데이터로드

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... 

하지만 난 싶지 않아 내 사용자는 데이터 세트부터 처리해야합니다 그걸 배경으로 할 수 있다면 항상 똑같아.

클래스의 첫 번째 인스턴스를 만들 때 글로벌 네임 스페이스에 데이터를로드하는 파이썬/표준 방법이 있습니까?

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

클래스 안에 넣으면, '__init__'이전에, 그것을 한 번만로드 할 것입니다. 'Dataset' 클래스에서 간단한'print()'를 사용해보십시오) 그리고보십시오. – TigerhawkT3

관련 문제