Python单体模式的几种常见实现方法详解

拾柒
拾柒
发布时间:2026-10-13| 5人浏览过
原创

本文详细解析Python中实现单体模式的多种技巧,包括修改父类__dict__的Borg模式、基于元类的__call__与__new__实现,以及利用类方法__new__和classmethod的巧妙方案。重点对比各方法的适用场景与参数细节,帮助开发者根据实际需求选择正确的单体实现路径。

本文介绍了Python中实现单体模式的几种主流方案,旨在为读者提供实用的参考代码与思路。

文中部分实现思路参考了StackOverflow上的讨论:https://stackoverflow.com/questions/1363839/python-singleton-object-instantiation/1363852#1363852

一、通过修改父类的 __dict__ 属性

class Borg:
  _shared_state = {}
  def __init__(self):
    self.__dict__ = self._shared_state
class Singleton(Borg):
  def __init__(self, name):
    super().__init__()
    self.name = name
  def __str__(self):
    return self.name
x = Singleton('sausage')
print(x)
y = Singleton('eggs')
print(y)
z = Singleton('spam')
print(z)
print(x)
print(y)

需要指出的是,这种实现方式并非严格意义上的单体模式。

接下来的几种方法则能实现真正的单体模式。

二、利用元类(Metaclass)实现

首先回顾一下元类的相关概念:

元类通常用于控制类的创建过程。

在定义类时,Python解释器需要确定该类使用的元类。解释器会优先查找类属性 __metaclass__,若存在则将其设为该类的元类;若未定义,则向上查找父类的 __metaclass__;若仍未找到 __metaclass__,则检查全局变量 __metaclass__;若以上均不存在,默认使用内置的 type 作为元类。

1. 继承 type,并重写 __call__ 方法

请注意 __call__ 方法的参数定义。

class Singleton(type):
  _instance = None
  def __call__(self, *args, **kw):
    if self._instance is None:
      self._instance = super().__call__(*args, **kw)
    return self._instance
class MyClass(object):
  __metaclass__ = Singleton
print(MyClass())
print(MyClass())

2. 继承 type,并重写 __new__ 方法

请注意 __new__ 方法的参数定义。

class Singleton(type):
  _instance = None
  def __new__(cls, name, bases, dct):
    if cls._instance is None:
      cls._instance = super().__new__(cls, name, bases, dct)
    return cls._instance
class MyClass(object):
  __metaclass__ = Singleton
print(MyClass())
print(MyClass())

3. 继承 object,并重写 __new__ 方法

请注意 __new__ 方法的参数定义。

class Singleton(object):
  _instance = None
  def __new__(cls):
    if cls._instance is None:
      cls._instance = super().__new__(cls)
    return cls._instance
class MyClass(object):
  __metaclass__ = Singleton
print(MyClass())
print(MyClass())

此外,还有一种较为巧妙的单体模式实现方式。

利用类方法 classmethod 进行控制

class Singleton:
  _instance = None
  @classmethod
  def create(cls):
    if cls._instance is None:
      cls._instance = cls()
    return cls._instance
  def __init__(self):
    self.x = 5    # or whatever you want to do
sing = Singleton.create()
print(sing.x) # 5
sec = Singleton.create()
print(sec.x) # 5

如需了解更多Python相关知识,可参考本站系列教程:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》以及《Python入门与进阶经典教程》。

希望上述内容能对您的Python编程实践有所帮助。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。