Skip to content Skip to sidebar Skip to footer

Creating Attributes Of Attributes - Possible?

I am dealing with monthly data for a number of different data sets (e.g. air temperature, ocean temperature, wind speeds etc), whereby each month and each data set will share simil

Solution 1:

Here's an example of how you could store everything internally in a dictionary and still reference the arrays as attributes as well as call functions on arrays by name:

import numpy as np


classData_Read:
    def__init__(self, monthly_shape=(200, 200, 40)): #3D data
        months = [
            "jan",
            "feb",
            "march",
            "april",
            "may",
            "june",
            "july",
            "august",
            "sept",
            "oct",
            "nov",
            "dec"
        ]
        self._months = {month: np.zeros(monthly_shape) for month in months}

    defdetrend(self, month):
        # this is a dummy function that just incrementsreturn self._months[month] + 1def__getattr__(self, name):
        if name in self._months:
            return self._months[name]
        returnsuper().__getattr__(name)

air_temp = Data_Read()
print(air_temp.jan.shape)  # (200, 200, 40)print((air_temp.detrend("jan") == 1).all())  # True

You can also achieve the same result using setattr and getattr because attributes are just stored in a dictionary on the object anyway:

import numpy as np


classData_Read:
    def__init__(self, monthly_shape=(200, 200, 40)): #3D data
        months = [
            "jan",
            "feb",
            "march",
            "april",
            "may",
            "june",
            "july",
            "august",
            "sept",
            "oct",
            "nov",
            "dec"
        ]
        for month in months:
            setattr(self, month, np.zeros(monthly_shape))

    defdetrend(self, month):
        # this is a dummy function that just incrementsreturngetattr(self, month) + 1

Post a Comment for "Creating Attributes Of Attributes - Possible?"