【问题标题】:Create the database only once instead of three times只创建一次数据库而不是三次
【发布时间】:2023-02-25 22:59:24
【问题描述】:

假设我有

class DataBuilder:
   def __init__(self):
      self.build()
   
   def build(self):
      #Place where the logic build the database
    

以及将继承该类的三个类

class StrategyOne(DataBuilder):
    def __init__(self):
         super().__init__()

class StrategyTwo(DataBuilder):
    def __init__(self):
         super().__init__()

class StrategyThree(DataBuilder):
    def __init__(self):
         super().__init__()

顾名思义,DataBuilder 类构建了一个大数据集。假设我打电话

strategy_one = StrategyOne()
strategy_two = StrategyTwo()
strategy_three = StrategyThree()

它会建立三次数据库吗?如果是这样,我怎样才能避免这样的事情?我只想建立一次数据库,然后创建上述三个对象。

【问题讨论】:

  • 这取决于你如何编写代码。数据库可以存储为类变量,默认设置为None。然后仅当变量为None 时才构建数据库。
  • 让我修改代码,让它显而易见
  • 支持组合而不是继承。如果您只需要一次数据库,则只创建一次并将其传递给其他对象。关注点分离:将数据库与其他东西分开。单一职责:让你的类只做一件事。
  • @MichaelButscher 你能告诉我你会如何处理这个吗?
  • @ThomasWeller 我是 Python 的新手。你能用一个例子给出完整的答案吗,这样我就能很好地理解

标签: python class inheritance


【解决方案1】:

一种选择是将数据库存储为类变量以最多拥有一个数据库:

class DataBuilder:
   database = None

   def __init__(self):
      self.build()
   
   def build(self):
      if database is None:
         # Build database and store it in the variable "database"
      # else: Do nothing

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2013-05-26
    • 2021-08-25
    • 2016-09-07
    • 1970-01-01
    相关资源
    最近更新 更多