pythonclassoop

What is the correct way of coding this classes 'linked' to each other


I have 2 classes i defined in this way:

def process_data(data):
    ### [...] here makes all the processing of the data
    return model  ## model is a class Model object

class A:
    def __init__(self, data) -> None:
        self.model = process_data(data) 
        pass
    def test1_on_model(self):
        ### run some tests and prints the results
        pass
    def test2_on_model(self):
        ### run some other tests and prints the results
        pass

class B:
    def __init__(self, model) -> None:
        self.model = model
        pass
    def test1_on_model(self):
        ### run some tests and prints the results
        pass
    def test2_on_model(self):
        ### run some other tests and prints the results
        pass

As you can see class A is simply starting from raw data to make a model object while class B takes directly the model object. I need those helper functions (test1_on_model...) to be callable on the instances of both class A and B.

I am sure there is a clean way to make it work, like using super or something else. But I am not familiar with it and so I cannot think of how to implement it in this case.


Solution

  • You can also use class methods:

    def process_data(data):
        ### [...] here makes all the processing of the data
        return model  ## model is a class Model object
    
    class C:
        def __init__(self, model) -> None:
            self.model = model
            pass
        @classmethod
        def from_raw_data(cls, data):
            return cls(process_data(data))
        def test1_on_model(self):
            ### run some tests and prints the results
            pass
        def test2_on_model(self):
            ### run some other tests and prints the results
            pass
    

    So you can create an object from a model (like class b) or like class A using C.form_raw_data(data)