我有一个自动化测试,使用一个函数来创建截图到一个文件夹中。多个截图实例都会调用该函数。在每次测试运行时,都会创建一个新的文件夹,因此我不需要考虑计数器重置的问题。为了反映这些截图的拍摄顺序,我需要想出可以按顺序排序的名称。这是我的解决方案:
def make_screenshot_file(file_name):
order = Counter().count
test_suites_path = _make_job_directory()
return make_writable_file(os.path.join(test_suites_path,'screenshot',file_name % order))
class Counter():
__counter_instance = None
def __init__(self):
if Counter.__counter_instance is None:
self.count = 1
Counter.__counter_instance = self
else:
Counter.__counter_instance.count += 1
self.count = Counter.__counter_instance.count
对我来说这很好用。但是我一直在想,是否有更简单的方法来解决这个问题呢?如果单例是唯一的方法,那么我的代码能否进行优化呢?
Counter
实例,它们都指向一个“特殊实例”。这与仅拥有一个实例不同。 - abarnert__counter_instance
的属性,为什么不直接创建一个count
类属性呢? - abarnert