Python 简明教程

Python - Singleton Class

在 Python 中, Singleton class 是单例设计模式的实现,这意味着这种类型的类只能有一个对象。当你执行一些繁重的操作时,比如创建一个数据库连接,这有助于优化内存使用。

In Python, a Singleton class is the implementation of singleton design pattern which means this type of class can have only one object. This helps in optimizing memory usage when you perform some heavy operation, like creating a database connection.

如果我们尝试为单例类创建多个对象,对象只会第一次被创建。在此之后,将会返回相同对象实例。

If we try to create multiple objects for a singleton class, the object will be created only for the first time. After that, the same object instance will be returned.

Creating Singleton Classes in Python

我们可以通过如下方式创建并实现 Python 中的单例类:

We can create and implement singleton classes in Python using the following ways −

  1. using init

  2. using new

Using init

init 方法是一个实例方法,用于初始化新建的对象。当从类创建对象时,它会被自动调用。

The init method is an instance method that is used for initializing a newly created object. It’s automatically called when an object is created from a class.

如果我们使用这个方法和一个静态方法,并提供必要的检查(即:类的实例是否存在),我们可以在创建了第一个对象后限制创建新对象。

If we use this method with a static method and provide necessary checks i.e., whether an instance of the class already exists or not, we can restrict the creation of a new object after the first one is created.

Example

在下面的示例中,我们正在使用 init 方法创建单例类。

In the below example, we are creating a singleton class using the init method.

class Singleton:
  __uniqueInstance = None

  @staticmethod
  def createInstance():
    if Singleton.__uniqueInstance == None:
      Singleton()
    return Singleton.__uniqueInstance

  def __init__(self):
      if Singleton.__uniqueInstance != None:
          raise Exception("Object exist!")
      else:
          Singleton.__uniqueInstance = self

obj1 = Singleton.createInstance()
print(obj1)
obj2 = Singleton.createInstance()
print(obj2)

当我们运行以上代码时,它将展示以下结果:

When we run the above code, it will show the following result −

<__main__.Singleton object at 0x7e4da068a910>
<__main__.Singleton object at 0x7e4da068a910>

Using new

new 方法是 Python 中一个特殊静态方法,被用来创建类的全新实例。它将类本身作为第一个参数,并返回该类的一个新实例。

The new method is a special static method in Python that is called to create a new instance of a class. It takes the class itself as the first argument and returns a new instance of that class.

当 Python 类的实例被声明时,它在内部调用 new () 方法。如果你想实现单例类,你可以覆盖此方法。

When an instance of a Python class is declared, it internally calls the new() method. If you want to implement a Singleton class, you can override this method.

在覆盖方法中,你首先检查类的实例是否存在。如果不存在(即:实例为 None),你调用 super() 方法来创建新对象。最后,将此实例保存在类属性中并返回结果。

In the overridden method, you first check whether an instance of the class already exists. If it doesn’t (i.e., if the instance is None), you call the super() method to create a new object. At the end, save this instance in a class attribute and return the result.

Example

在下面的示例中,我们正在使用 new 方法创建单例类。

In the following example, we are creating a singleton class using the new method.

class SingletonClass:
   _instance = None

   def __new__(cls):
      if cls._instance is None:
         print('Creating the object')
         cls._instance = super(SingletonClass, cls).__new__(cls)
      return cls._instance

obj1 = SingletonClass()
print(obj1)

obj2 = SingletonClass()
print(obj2)

上述代码的结果如下:

The above code gives the following result −

Creating the object
<__main__.SingletonClass object at 0x000002A5293A6B50>
<__main__.SingletonClass object at 0x000002A5293A6B50>