[Python] How to have a child dataclass inherit from a parent, where updating attributes from...

Discussão em 'Python' iniciado por Stack, Fevereiro 5, 2025.

  1. Stack

    Stack Membro Participativo

    I am not sure whether this is possible but is there a way for attributes of a child dataclass to be dependent on methods being called in the parent dataclass? The reason is that I want the parent dataclass to represent the raw data and then the child class to represent transformed data. Then if the raw dataclass is updated, methods from the child class are called and update the attributes for the transformed dataclass (and the updated x is propagated to the transformed_data permanently.

    So when I call raw_data.update_value(), then both transformed_data._partition_dependents() and transformed_data._interpolate() are called without needing to explicitly code that.

    I understand if I passed objects to RawData and then update the objects without making a copy, they will propagate, but I also want to use float and int type for attributes from RawData to be used in the tansformed_data._interpolate() method

    I was thinking of using the class attributes in RawData, but I want to be able to initialise different RawData with multiple different parameters, and still not sure how to trigger the methods in TransformedData

    from dataclasses import dataclass, field
    import numpy as np

    @dataclass
    class RawData:
    x: np.ndarray
    y: np.ndarray

    def update_values(self, x, y):
    self.x = x
    self.y = y


    @dataclass
    class TransformedData(RawData):
    n_x: int
    x_interp: np.ndarray = field(default_factory=lambda: np.array([]))
    y_interp: np.ndarray = field(default_factory=lambda: np.array([]))

    def __post_init__(self):
    self._partition_dependents()
    self._interpolate()

    def _partition_dependents(self):
    self.x_interp = np.linspace(self.x.min(), self.x.max(), self.n_x)

    def _interpolate(self):
    self.y_interp = np.interp(self.x_interp, self.x, self.y)


    x_original = np.arange(10)
    y_original = x_original ** 2
    n_x = 100

    raw_data = RawData(x_original, y_original)

    transformed_data = TransformedData(n_x)

    x_new = np.arange(20)
    y_new = x_new ** 2

    raw_data.update_values(x_new, y_new) # Then _partition_dependents() and _interpolate() to both trigger for transformed_data

    transformed_data.y[-1] # Should be 19**2
    raw_data.x[-1] == transformed_data.x[-1] # Should be true

    Continue reading...

Compartilhe esta Página