【Python】 Python 中实现单例模式?

在 Python 中,实现单例模式通常有多种方法。以下是使用类装饰器实现单例模式的方法:

```python

def singleton(cls):

instances = {}

def get_instance(*args, **kwargs):

if cls not in instances:

instances[cls] = cls(*args, **kwargs)

return instances[cls]

return get_instance

@singleton

class MyClass:

def init(self):

self.value = 0

def increment(self):

self.value += 1

class AnotherClass:

@staticmethod

def my_static_method():

print("This is a static method")

@singleton

class AnotherSingletonClass:

def init(self):

self.value = 0

def increment(self):

self.value += 1

Test the singleton classes

if name == "main":

my_instance = MyClass()

another_instance = AnotherClass()

another_singleton_instance = AnotherSingletonClass()

my_instance.increment()

another_instance.my_static_method()

another_singleton_instance.increment()

print(my_instance.value) # Output: 1

print(another_instance is AnotherClass.my_static_method()) # Output: True

print(another_singleton_instance.value) # Output: 1

```

在这个例子中,我们定义了一个类装饰器 `singleton`,它接受一个类作为参数,并返回一个单例对象。`singleton` 装饰器使用字典 `instances` 来存储已经创建的实例。当我们尝试创建类的实例时,如果该类已经在 `instances` 字典中,则返回已有的实例;否则,创建新的实例并存储在 `instances` 字典中。

我们还定义了两个类 `MyClass` 和 `AnotherClass`,它们分别具有一个实例方法和静态方法。我们还定义了两个单例类 `MyClass` 和 `AnotherSingletonClass`,它们具有相同的实例方法和静态方法。

在测试部分,我们创建了 `MyClass`、`AnotherClass` 和 `AnotherSingletonClass` 的实例,并调用了它们的实例方法和静态方法。从输出中可以看出,`MyClass` 和 `AnotherSingletonClass` 的实例方法输出了相同的值,这是因为它们是同一个类的实例;而 `AnotherClass` 的静态方法输出了与 `AnotherSingletonClass` 的静态方法相同的输出,这是因为它们都是同一个类的静态方法。

相关推荐
uoKent3 分钟前
c++中的运算符重载
开发语言·c++
hahahahanhanhan5 分钟前
Tensorflow使用GPU(cuda和cudnn和tensorflow下载)
人工智能·python·tensorflow·gpu
深度学习lover8 分钟前
<数据集>yolo毛毛虫识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·毛毛虫识别
你撅嘴真丑9 分钟前
第五章 C++与STL入门
开发语言·c++
坐在地上想成仙9 分钟前
从机床到键盘:用机械设计思维写出一个可部署网页
java·c++·python
Allen_LVyingbo9 分钟前
用Python实现辅助病案首页主诊断编码:从数据清洗到模型上线(上)
开发语言·python·github·知识图谱·健康医疗
CoderCodingNo13 分钟前
【GESP】C++五级练习题 luogu-P2242 公路维修问题
开发语言·c++·算法
傻啦嘿哟13 分钟前
Python家庭支出统计:从Excel到可视化图表的完整指南
开发语言·python·excel
子夜江寒15 分钟前
OpenCV部分操作介绍
图像处理·python·opencv·计算机视觉
轻竹办公PPT15 分钟前
2026 年 AI PPT 工具深度复盘:工具间的效率鸿沟与职场应用场景分析
人工智能·python·powerpoint