【问题标题】:Python parent-child design patternPython 父子设计模式
【发布时间】:2021-03-18 20:04:22
【问题描述】:

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

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

我尝试的结构是:

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

但是,我意识到这可能不是最好的方法,因为很难从父对象调用子方法。

这是一个例子:

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)

我对设计模式的思考还很陌生,因此非常感谢任何帮助!

【问题讨论】:

  • 你想做什么?设计模式取决于您的使用,如果您想要动态布局,则需要工厂模式,例如,如果您想要交叉图形交互,则需要观察者模式等
  • 我希望能够只实例化父类并让父类做其他所有事情(通过调用子方法),这很难解释,我可能不使用类就保留它

标签: python python-3.x design-patterns plotly-dash


【解决方案1】:

我了解您试图在共存类之间创建链接,并且 Parent 和 Child 类确实与父母及其孩子相关(因为声明了疫苗接种数据)。 在这种情况下,您可以创建一个父类(Person)和 2 个子类(Parent 和 Child)。 因此,您可以组织代码以将两个子类都需要访问的方法留在父类上。 尝试通过编码链接类(例如在需要输入 Parent 实例的 Child 的 init 方法上实例化一个变量)。

【讨论】:

  • 谢谢,所以你的意思是我应该有一个顶级类(Person)然后父类和子类将是 person 的子类?这是否意味着父母和孩子是兄弟姐妹?
  • 是的,他们是兄弟姐妹。如果这两个类不能仅由一个类表示,则另一种选择是评估。我不确定,看看你发布的那段代码,但也许合并它们会让你的代码更清晰。如果您只使用 Parent 来实例化 Child 有方法,为什么不创建一个包含所有这些方法的单个类?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
  • 2019-09-23
  • 2010-10-11
  • 1970-01-01
相关资源
最近更新 更多