在面向对象编程中避免重复数据库连接的最佳方法

问题描述

这是 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()

不想通过connect()显式调用MyApp().connect()方法,所以在__init__方法itsef中添加。 (如果有更好的方法,请提出建议,__new__() 在这种情况下会有所帮助吗?)

[输出]

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

[预期]

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

我不想一次又一次地创建一个实例。任何建议/建议将不胜感激。谢谢,

解决方法

问题是 self.instance 出在 实例上。您想要的是将其作为类属性,以便所有实例都具有该信息。要访问它,请使用 self.__class__.instance。此外,在 Python3 中,类不需要从 object 继承。

>>> class MyApp:
...     instance = None
...
...     def __init__(self):
...         self.connect()
...
...     def connect(self):
...         if self.__class__.instance is None:
...             print('connecting')
...             self.__class__.instance = 1
...
>>>
>>> a = MyApp()  # will connect the first time
connecting
>>> b = MyApp()  # no new connection
>>> a.connect()  # no new connection
>>> b.connect()  # no new connection

(顺便说一句,特别是在这种情况下,instance 不是一个好名字,因为它正好相反。使用 connected = True/False 代替。)

如果 connect() 不需要访问其他实例变量,它可以是一个 classmethod 并使用 cls.instance

>>> class ... # as before
...     @classmethod
...     def connect(cls):  # cls is the class
...         if cls.instance is None:
...             print('connecting')
...             cls.instance = 1