jeudi 18 mars 2021

Python parent-child design pattern

I realize the title is terrible, please feel free to change it or suggest changes to it (I am new to design patters)

I have a Python based Dash web app (not completely relevant) and I want to add some structure to it, however I am not sure what kind of design pattern to use.

The structure I tried was:

-- Parent object (initializes all the configuration and instantiates a data object that the rest of the children will need to use)
|
|- Have child objects with methods that return the layout, which I want to be able to call from the parent object

However, I realized this is probably not the best approach since it is difficult to call a child method from the parent object.

Here is an example:

class Parent:
    def __init__(self):
        self.data = VaccinationData() <-- created parent so I can use this data in entire project
        self.app = dash.Dash()
        self.set_layout()

    def set_layout(self):
        self.app.layout = html.Div(self.child_method()) <-- calling child method

class Child(Parent):
    def child_method(self):
        # Does some data processing with self.data
        return html.Div(
            className="right",
            children=[self.top_stats(), self.pred_full_vacc()], <-- calling more child's child methods
        )
    
if __name__ == "__main__":
    app = Parent()
    app.app.run_server(debug=True)

I am quite new to thinking about design patters so would appreciate any help!

Aucun commentaire:

Enregistrer un commentaire