我有一个遵循单例模式的类,如下所示。在Python模块automaton.py中,我有:
class Automaton(object):
def launch_probe(self):
if hasattr(self, 'launched') and self.launched:
return
print "Launched!"
self.launched = True
automaton = Automaton()我从各种其他模块中调用对象上的方法。我不会在其他地方实例化这个类,我希望经常调用方法或访问属性,所以像这样保持对它的访问是很好的:
from automaton import automaton
automaton.launch_probe()
print 'Status:'
print automaton.launched但是,现在我正致力于更好地测试这段代码,并希望在setUp()中重置单元测试之间的单例。
import automaton
def setUp():
automaton.automaton = automaton.Automaton()然而,这并不能完成工作,因为其他加载的模块都有对原始Singleton的引用。我可以切换到使用Automaton.get_instance()获取单例的模式,或者只是导入模块并引用该模块中的变量,但我发现这会使主要产品代码更冗长,更难理解。我曾考虑让automaton变量成为描述符,这样它就具有了智能性,但我发现描述符只能在类中工作。我考虑的最后一种方法只是试图通过清除它的字典并调用它的__init__方法来重新初始化现有的Automaton实例。对于这样的事情,推荐的方法是什么?
发布于 2016-12-18 02:31:53
许多可用选项之一是提供一种将单例重置为状态零(初始状态)的方法,例如:
class Automaton(object):
def __init__(self):
self.reset()
def reset(self):
self.launched = False
def launch_probe(self):
if hasattr(self, 'launched') and self.launched:
return
print("Launched!")
self.launched = True
automaton = Automaton()
if __name__ == "__main__":
import unittest
class Test(unittest.TestCase):
def setUp(self):
automaton.reset()
def test1(self):
automaton.launch_probe()
self.assertEqual(automaton.launched, True)
def test2(self):
self.assertEqual(automaton.launched, False)
unittest.main()https://stackoverflow.com/questions/41176082
复制相似问题