-1

I'm new to Python and trying to create a class with multiple attributes. I would like to access the attributes like the following:

measured_dataset.date
measured_dataset.temperature1
measured_dataset.temperature2

The attributes date, temperature1, and temperature2 will be variables with lists:

measured_date = [1,2,3]
measured_dataset = dataset('date', measured_date)

I tried to create a class like:

class dataset :

    def __init__(self, name, value = []) :

        self.name = name
        self.parameter = parameter

But somehow I'm only able to create measured_dataset.name.

How can I create what I want?

martineau
  • 119,623
  • 25
  • 170
  • 301
ulix
  • 1
  • 1
  • Class names should follow the `lower_case_with_underscores` style. You're using a list as a default argument, **be careful**! https://stackoverflow.com/q/1132941/11301900 – AMC Jan 26 '20 at 21:33

2 Answers2

1

You can use properties to define "aliases" around existing attributes.

class Dataset :

    def __init__(self, name, values) :
        self.name = name
        self.parameter = parameter

    @property
    def date(self):
        return self.parameter[0]

    @property
    def temperature1(self):
        return self.parameter[1]

    @property
    def temperature2(self):
        return self.parameter[2]

However, it seems odd to store the values in a list just because you are providing them as a list. __init__ can unpack the list and store the attributes directly:

class Dataset:
    def __init__(self, name, values):
        self.name = name
        self.date = values[0]
        self.temperature1 = values[1]
        self.temperature2 = values[2]

or even better, make those values named parameters to __init__, and delegate the unpacking to a class method.

class Dataset:
    def __init__(self, name, date, temp1, temp2):
        self.name = name
        self.date = date
        self.temperature1 = temp1
        self.temperature2 = temp2

    @classmethod
    def from_list(cls, name, values):
        return Dataset(name, values[0], values[1], values[2])
chepner
  • 497,756
  • 71
  • 530
  • 681
0

You can't name class attributes in one way and then try to get them with another names. You can do this instead:

class Dataset :

    def __init__(self, date, temperature1, temperature2) :
        self.date = date
        self.temperature1 = temperature1
        self.temperature2 = temperature2

measrued_dataset = Dataset('2020-01-26', 100, 200)

And same thing dynamically (while you should avoid doing this in general cases):

class Dataset:
    def __init__(self, **kwdargs):
        self.__dict__.update(kwdargs)

measrued_dataset = Dataset(date='2020-01-26', temperature1=100, temperature2=200)
Charnel
  • 4,222
  • 2
  • 16
  • 28