vendredi 12 mars 2021

Best approach to avoid repetitive database connection in Object Oriented Programming

Here is the sample code in Python.

[sample.py]

class MyApp(object):
     
      def __init__(self):
         self.instance = None

         self.connect()


    def connect(self):
        if self.instance is None:
            print('Connecting to DB...')
            self.instance = 1 # Assume connected
        return self.instance

[A.py]

from sample import MyApp
from B import again

a = MyApp()
again()

[B.py]

from sample import MyApp

def again():
    b = MyApp()

Wouldn't like to call the connect() method explicitly by MyApp().connect(), so that added in __init__ method itsef. (Please do advice if any better approach is available, Is __new__() will be helpful in this context?)

[Output]

>> python A.py
Connecting to DB...
Connecting to DB...

[Expected]

>> python A.py
Connecting to DB...

I don't want to create an instance again and again. Any suggestion/advise would be grateful. Thanks,

Aucun commentaire:

Enregistrer un commentaire