【问题标题】:Single instance of class in PythonPython中类的单个实例
【发布时间】: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 中应该避免使用单例,因此我很好奇这类问题的最佳实践是什么?

【问题讨论】:

  • 阅读 Borg 设计模式 herehere 了解将类转换为单例的简单方法。还有其他方法。
  • 我会将类本身用作单例。这种方法我从来没有遇到过问题。
  • 您在其他模块中所说的import SocketCommunication 将不起作用,因为SocketCommunication 是您的一个类的名称。它需要类似于from my_module import SocketCommunication 才能使下一行有效。也就是说,您可以有效地使该类成为在定义类之后在my_module.py 文件中添加SocketCommunication = SocketCommunication() 的单例。这样就很难再创建更多的实例,因为类名将被其自身的一个实例所覆盖。

标签: python class sockets singleton instance


【解决方案1】:

以下是在 Python 中使用单例的三种方式。 使用metaclassdecorator 达到目标。

  1. 使用__new__

     class Singleton(object):
         def __new__(cls, *args, **kw):
             if not hasattr(cls, '_instance'):
                 orig = super(Singleton, cls)
                 cls._instance = orig.__new__(cls, *args, **kw)
             return cls._instance
    
     class MyClass(Singleton):
         a = 1
    
     one = MyClass()
     two = MyClass()
    
     two.a = 3
     print one.a
     #3
     print id(one)
     #29097904
     print id(two)
     #29097904
     print one == two
     #True
     print one is two
     #True
    
  2. 使用__metaclass__

class Singleton2(type):
    def __init__(cls, name, bases, dict):
        super(Singleton2, cls).__init__(name, bases, dict)
        cls._instance = None

    def __call__(cls, *args, **kw):
        if cls._instance is None:
            cls._instance = super(Singleton2, cls).__call__(*args, **kw)
        return cls._instance


    class MyClass2(object):
        __metaclass__ = Singleton2

    one = MyClass2()
    two = MyClass2()

    two.a = 3
    print one.a
    #3
    print id(one)
    #31495472
    print id(two)
    #31495472
    print one == two
    #True
    print one is two
    #True
  1. 使用decorator

      def singleton(cls, *args, **kw):
         instances = {}
         def _singleton(*args, **kw):
            if cls not in instances:
                 instances[cls] = cls(*args, **kw)
            return instances[cls]
         return _singleton
    
     @singleton
     class MyClass3(object):
         a = 1
         def __init__(self, x=0):
             self.x = x
    
     one = MyClass3()
     two = MyClass3()
    
     two.a = 3
     print one.a
     #3
     print id(one)
     #29660784
     print id(two)
     #29660784
     print one == two
     #True
     print one is two
     #True
     one.x = 1
     print one.x
     #1
     print two.x
     #1
    

我更喜欢使用decorator

【讨论】:

  • 装饰器参数*args**kwargs 应该是_singleton 方法的输入,而不是singleton 类,不是吗?
  • 装饰器解决方案的一个警告可能是,如果你有类变量,这个单例将用函数替换类,并且通过MyClass.CLASS_VAR 访问该变量将丢失。
【解决方案2】:

单例是有争议的,因为它们经常被用作包装全局变量的一种方式。这就是为什么有些人主张避免。全局变量使测试更难,它们限制访问控制,并且经常导致变量之间的强耦合。 (有关为什么全局变量通常是不好的做法的更多详细信息,请参阅http://wiki.c2.com/?GlobalVariablesAreBad

在您的特定场景中,使用单例很可能是合适的,因为您只是试图阻止 SocketCommunication 被多次初始化(有充分的理由),而不是尝试将其用作全局状态的容器。

请参阅 Are Singletons really that bad?What is so bad about singletons? 了解有关单例的一些讨论。

【讨论】:

  • 感谢您的回答。似乎在这种特殊情况下,当我只需要一个类的单个实例时,单例是最好的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
  • 2013-06-10
相关资源
最近更新 更多