Python parent-child 设计模式

Python parent-child design pattern

我意识到标题很糟糕,请随时更改或建议更改(我是设计模式的新手)

我有一个基于 Python 的 Dash 网络应用程序(不完全相关),我想为其添加一些结构,但是我不确定要使用哪种设计模式。

我尝试的结构是:

-- 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

但是,我意识到这可能不是最好的方法,因为很难从 parent object.

调用 child 方法

这是一个例子:

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)

我对设计模式的思考还很陌生,所以非常感谢您的帮助!

我知道你试图在 classes 之间创建一个 link 共存,而 Parent 和 Child classes 确实与a parent 和他们的 children(因为有疫苗接种数据声明)。 在这种情况下,您可以创建一个 parent class(人)和 2 个 child classes(Parent 和 Child)。 因此,您可以组织代码,将 child class 都需要访问的方法保留在 parent class 上。 尝试通过编码 link classes(比如在 Child 的 init 方法上实例化一个需要 Parent 的变量要输入的实例)。