Python-在类的第一个实例上加载数据

eri*_*nla 6 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...
Run Code Online (Sandbox Code Playgroud)

但我不希望我的用户必须处理数据集,因为如果我可以在后台执行它,它总是相同的。

当我创建类的第一个实例时,是否有一种 pythonic/canonical 方法将数据加载到全局命名空间中?我希望有这样的事情:

class Class_using_dataset():
    def __init__(self):
        if dataset doesn't exist:
             load dataset into global namespace
        use dataset
Run Code Online (Sandbox Code Playgroud)

Alb*_*oso 6

您可以在解析类时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()
Run Code Online (Sandbox Code Playgroud)

对于第二个,分配None给类变量,并且仅在__init__方法中加载数据集(如果ds是)None

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()
Run Code Online (Sandbox Code Playgroud)