【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` 的静态方法相同的输出,这是因为它们都是同一个类的静态方法。

相关推荐
七夜zippoe8 分钟前
TensorFlow 2.x深度实战:从Keras API到自定义训练循环
人工智能·python·tensorflow·keras
励ℳ8 分钟前
Python环境操作完全指南
开发语言·python
ljxp123456814 分钟前
二叉树中序遍历算法详解
python
invicinble17 分钟前
centos7系统安装jdk
java·开发语言
御坂10101号20 分钟前
JIT 上的 JIT:Elysia JS 的优化实践与争议
开发语言·javascript·网络·性能优化·node.js·express
山野02035 分钟前
index.php 和 php
开发语言·php
麦德泽特1 小时前
蓝牙与WiFi之外:为机器人选择合适的近距离无线通信技术
c语言·开发语言·安全·机器人·ssh
Web打印1 小时前
Phpask(php集成环境)之02配置php
开发语言·php
查无此人byebye1 小时前
【超详细解读(GPU)】基于DiT的MNIST扩散模型(DDPM)完整实现
python·深度学习·nlp·transformer·多分类
赵谨言1 小时前
基于Python和ArcPy的不动产数据入库技术与运用
大数据·开发语言·经验分享·python