问题:**你想在 Python 中实现一个单例类,以确保只创建该类的一个实例。

解决方案: 要在 Python 中实现单例类,可以使用 __new__ 方法来控制类的实例化。

下面是一个 Python 单例类的简单示例:

class Singleton:
  _instance = None  # Private class variable to store the single instance

  def __new__(cls):
    if cls._instance is None:
      cls._instance = super(Singleton, cls).__new__(cls)
    return cls._instance

# Usage
singleton_1 = Singleton()
singleton_2 = Singleton()

print (singleton_1 is singleton_2) # True (Both variables refer to the same instance)

有没有简单、优雅的方法来实现一个单例类 在本例中,我们使用 __new__ 方法来控制实例的创建。_instance 变量用于存储单个实例。创建单例类的实例时,它会检查实例是否已经存在。如果存在,则返回现有实例;否则,创建一个新实例并将其存储在 _instance 变量中。

这种方法确保只创建一个 Singleton 类的实例,使它成为在 Python 中定义单子的一种简单而优雅的方法。