我需要在 Python (2.7) 中实现单例模式并使用单元测试覆盖代码。
下面是我使用的代码:
class Singleton(object):
def __new__(cls):
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__new__(cls)
return cls.instance
为了使单元测试独立,我需要为此类实现一个析构函数。如何做到这一点?
最佳答案
您可以只删除instance
属性:
del Singleton.instance
如果您要对其进行子类化,则可以将其设为类方法:
@classmethod
def clear_instance(cls):
del cls.instance
关于python - 用于 Python 单元测试的单例析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31426026/