Search code examples
pythonclassinheritanceinstance

Create the database only once instead of three times


Suppose I have

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

and three classes which will inherit of that class

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

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

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

As the name explains, the class DataBuilder builds a big dataset. Suppose I call

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

Will it build the database three times? If so, how can I avoid such thing? I just want to build the database once and then creates the three above object.


Solution

  • You could make a boolean variable and set it to false, then once database is built, you could switch it to true. A database will be built only if value of that that variable is false. For example:

    class DataBuilder:
      database_exists = False
      def __init__(self):
        self.build()
    
      def build(self):
        if database_exists:
          # do nothing
        else: 
          # your database code