How to have a "childlike" class instance method trigger when a "parentlike" instance attribute is updated?

I am trying to get the behaviour where childlike class instance method is triggered as a response to an instance attribute of a parent is updated. The child class can inherit from the parent if that's the only way to do it. I am aware of observers/callbacks and then triggering the callback functions after the update, but I want the normalise to be called without explicitly coding it up.

In other words, I want Normalised.normalise() to be bounded to Raw.x.

Constraints:

The reason is that I am currently doing a large project, where I have a lot of methods from different classes bounded to the instance attribute, Raw.x, and they will always have this relationship.

import numpy as np
import time

class Raw:
    def __init__(self, x):
        self._x = x  

    @property
    def x(self):
        return self._x
    
    @x.setter
    def x(self, new_value):
        self._x = new_value
        
    def update_values(self, counter):
        self.x = self.x + counter + np.random.normal(0,0.3)
        
class Normalised:
    def __init__(self, raw_obj: Raw, name=""):
        self.raw = raw_obj  
        self.name = name
        self.norm=self.normalise()
        
    @property
    def normalise(self):
        x = self.raw.x  
        self.norm = (x - x.min()) / (x.max() - x.min())
        print(self.norm)
        return self.norm

data_1 = Raw(np.arange(10))
data_2 = Raw(20 * np.arange(10))

data_normalised_1 = Normalised(data_1, "object_1")
data_normalised_2 = Normalised(data_2, "object_2")

while True:
    data_1.update_values(1)
    data_2.update_values(2)
    time.sleep(2)

I DON'T want to use something like:

class Raw:
    def __init__(self, x,):
        self._x = x  
        self.callbacks=[]
        
    def add_callback(self,callback):
        self.callbacks.append(callback)
        
    def update_values(self, counter):
        self.x = self.x + counter + np.random.normal(0,0.3)
        
        for callback in self.callbacks:
            callback(self.x)
    
class Normalised:
    def __init__(self, raw_obj: Raw, name=""):
        self.raw = raw_obj  
        self.name = name
        self.norm=self.normalise()
        raw_obj.add_callback(self.normalise)
        
    def normalise(self, x): 
        self.norm = (x - x.min()) / (x.max() - x.min())
        return self.norm

And also not like:

class Raw:
    def __init__(self, x, normal_obj):
        self._x = x  
        self.normal_obj=normal_obj
     # rest of code
     
     
    def update_values(self, counter):
        self.x = self.x + counter + np.random.normal(0,0.3)
        self.normal_obj.normalise()

Upvotes: 0

Views: 43

Answers (0)

Related Questions