我在创建类的实例来测试它们的函数内部运行for循环。而不是创造新的课程,它似乎一遍又一遍地重复使用相同的两个课程。为什么python重用函数里面的类实例
有没有什么我想知道如何在python方法中处理类和变量?
我怎么能生成循环
class CollectionSetImages(unittest.TestCase):
def test_keywordset(self):
"""Testing keyword queries by images equality """
for keyword in ['a','b','c','d','e','f','g']:
images_by_keyword = Image.keyword_query([keyword])
collection = Collection([keyword])
class_images = collection.images
print('colleciton: %s id: %s' % (collection,id(collection)))
self.assertEqual(images_by_keyword, class_images,)
这里的每个迭代一个新的对象是输出
colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656cc> id: 3083228876
colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656ec> id: 3083228908
colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656cc> id: 3083228876
colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656ec> id: 3083228908
colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656cc> id: 3083228876
colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656ec> id: 3083228908
colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656cc> id: 3083228876
当我使用单独的变量名,我得到的每个实例单独的ID作为预期:
collectionA = Collection(['a'])
print('collection: %s id: %s' % (collectionA,id(collectionA)))
collectionB = Collection(['f'])
print('collection: %s id: %s' % (collectionB,id(collectionB)))
collectionC = Collection(['f'])
print('collection: %s id: %s' % (collectionC,id(collectionC)))
输出:
collection: <tests.fakeimages._FakeCollection object at 0xb7cbc8ac> id: 3083585708
collection: <tests.fakeimages._FakeCollection object at 0xb7cbccec> id: 3083586796
collection: <tests.fakeimages._FakeCollection object at 0xb7cbcd2c> id: 3083586860
看起来你已经有了一个测试模拟对象......你可能希望仔细检查你的模拟类的实例如何在测试用例中发挥作用。 – 2009-12-09 21:15:43
@Jarret,很好,发布测试对象的输出很快 – 2009-12-09 21:19:15