【发布时间】:2017-02-14 22:55:42
【问题描述】:
我正在创建一个 Python 应用程序,其中包括与服务器的套接字通信。我想要一个可以在我的整个应用程序中使用的模块(其他几个模块)。目前我的模块如下所示:
class SocketCommunication:
def __init__(self):
self.socketIO = SocketIO(settings.ADDRESS, settings.PORT, Namespace)
def emit(self, message, data):
json_data = json.dumps(data.__dict__)
self.socketIO.emit(message, json_data)
class Namespace(BaseNamespace):
def on_connect(self):
print '[Connected]'
def on_disconnect(self):
print "[Disconnected]"
当我在其他模块中使用它时,我会执行以下操作:
import SocketCommunication
self.sc = SocketCommunication()
问题是每次我这样做时,都会创建一个新连接,该连接将在服务器上显示为新客户端,这是不可取的。 据我所知,在 Python 中应该避免使用单例,因此我很好奇这类问题的最佳实践是什么?
【问题讨论】:
-
我会将类本身用作单例。这种方法我从来没有遇到过问题。
-
您在其他模块中所说的
import SocketCommunication将不起作用,因为SocketCommunication是您的一个类的名称。它需要类似于from my_module import SocketCommunication才能使下一行有效。也就是说,您可以有效地使该类成为在定义类之后在my_module.py文件中添加SocketCommunication = SocketCommunication()的单例。这样就很难再创建更多的实例,因为类名将被其自身的一个实例所覆盖。
标签: python class sockets singleton instance