python - 如何根据输入创建单例类?

标签 python

我有一个类定义为

class Conditional_Singleton(object):
    def __init__(self, condition=None):
        self.initialization = some_func_of(condition)

由于“初始化”步骤确实需要花费大量时间来运行并且输出可能会很大,因此我真的希望在给定相同输入的情况下不要一遍又一遍地重新创建该类,但一旦输入发生变化就这样做。有任何想法吗?

最佳答案

class Conditional_Singleton(object):
    saved_insances = {}
    def __new__(cls, condition = None):
        if not condition in cls.saved_instances:
            cls.saved_instances[condition] = super(
                Conditional_Singleton, cls).__new__(cls)
        return cls.saved_instances[condition]
    def __init__(self, condition = None):
        if not hasattr(self, 'initialization'):
            self.initialization = some_func_of(condition)
        

这会将创建的实例的字典保存在类本身中,并在传递相同条件时自动重用它们。

编辑:刚刚看到您的评论。您需要找到一种散列 condition 的好方法才能使其发挥作用,因此除非它派生自实现 __hash__ 的类,否则您需要自己实现它。

编辑 2:使用 __new__ 而不是 __init__ 作为单例。

关于python - 如何根据输入创建单例类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6764338/

相关文章:

python - 条件内部 int(x) 方法,即使它不采用 bool 值

python - 使用ffmpeg从两个视频中同时提取帧

python - 在 Python 2.7.5 中比较字符串和 unicode

python - OCR的干净图像

python - 如何pickle ssl.SSLContext 对象

python - 如何从视频中提取音频?

python - 如何使用 Python 和 BS4 读取相邻 html 元素的内容?

python - 在 Anaconda 中安装雅虎财经软件包

Python 查找每月复利的固定付款

python - 用于训练的 Keras 特征形状