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



下面是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()

不希望MyApp().connect()显式调用connect()方法,因此在__init__方法中添加了自己。(如果有更好的方法,请给出建议,__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

最新更新