Search code examples
pythonpython-3.xpython-dataclasses

Proper way to use dataclass in another class


After asking my last question, it seems like I have not really understood classes adn dataclasses. So I would like to learn the correct way of doing the following:

  1. define dataclass
  2. define other class, which will use an instance of dataclass
  3. use a method from the second class to updatenvalues of dataclass

The way I do gives me an error saying that my datafram doesn't exist. I created a method inside the dataclass, using that results in an error stating it is read-only.

@dataclass(slots=True)
def Storage():
   timestamp: float
   value: float


class UDP():
    some attributes
    self.datastorage: Storage = Storage()

    def updatedata(self, time, val):
        self.datastorage.timestamp = time
        self.datastorage.value = val

def main():
    test = UDP()
    test.updatedata(0.01,2) 

So my question is how to instantiate a dataclass in another class and be able to manipulate the values in the dataclass?


Solution

  • Your code has several syntactic problems. Once those are fixed, the code works. Storage objects are mutable, and you may freely modify their timestamp and value attributes.

    In [7]: @dataclass(slots=True)
       ...: class Storage:
       ...:    timestamp: float
       ...:    value: float
       ...:
       ...:
       ...: class UDP:
       ...:     datastorage: Storage = Storage(0.0, 0.0)
       ...:
       ...:     def updatedata(self, time, val):
       ...:         self.datastorage.timestamp = time
       ...:         self.datastorage.value = val
       ...:
       ...: def main():
       ...:     test = UDP()
       ...:     test.updatedata(0.01,2)
       ...:
    
    In [8]: main()