1

I have a very large dataset in NetCDF4 format. Normally I would just read the variables I need and pass them as attributes to my custom class so I can create new methods for post processing. Since this dataset is so large, this is not an option as it throws a memory error. So I want to extend the attributes of the NetCDF4 Dataset instead. The following code illustrates what I'm trying to do:

import netCDF4
class output(NetCDF4.Dataset):
    def __init__(self, path):
        super(NetCDF4.Dataset, self).__init__(path)
        print(self.variables) # Prints successfully

    def my_new_method(self):
        print(self.variables) # AttributeError: 'output' object has no attribute 'variables'
Drise
  • 4,164
  • 5
  • 38
  • 64
Reniel Calzada
  • 73
  • 1
  • 10

2 Answers2

1

Your super() syntax is incorrect. Consider

class output(netCDF4.Dataset):
    def __init__(self, path):
        super(output, self).__init__(path)
        print(self.variables) 
    def my_new_method(self):
        print(self.variables)

The basic syntax of super() in Python has been discussed here before (see the linked post)

With this definition I could type

my_output=output("myhdf.hdf")
my_output.my_new_method()

Both commands output the list of variables.

Dmitri Chubarov
  • 14,705
  • 5
  • 36
  • 70
  • This was helpful, thanks! Although now I get a __getattribute__ error, but I guess that's material for a second question... – Reniel Calzada Mar 20 '18 at 11:55
0

The NetCDF4 developers helped me further, and this is the actual way of doing it:

import netCDF4

class output(netCDF4.Dataset):
    def __init__(self, *args, **kwargs):
        super(output, self).__init__(*args, **kwargs)
    def my_new_method(self):
        print(self.variables)

As pointed out by Dmitri Chubarov (see accepted answer) the super syntax was incorrect, but also one needs to pass *args and **kwargs or else you you will get additional errors.

Reniel Calzada
  • 73
  • 1
  • 10