2009-12-09 10 views
6

私はforループをテストするクラスのインスタンスを作成する関数の中で実行しています。新しいクラスを作る代わりに、同じ2つ以上のものを何度も何度も再利用しているようです。なぜ関数内でクラスインスタンスを再利用するのですか?

Pythonメソッドでクラスと変数がどのように処理されるかについて、私は何か不足していますか?予想通り、私はインスタンスごとに別々のIDを取得する別々の変数名を使用する場合、私はループここ

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 

です:

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 
+1

テストモックオブジェクトがあるようです...テストケースでモッククラスのインスタンス化がどのように機能するかを再確認したい場合があります。 –

+0

@ジャレット、良い点、試験対象の出力をすぐに投稿 –

答えて

11

これは、オブジェクトのメモリが再利用されており、新しいオブジェクトがインスタンス化されていないことを示しています。各反復ではcollectionが上書きされているため、以前のオブジェクトの参照カウントが低下し、Pythonインタプリタはそのメモリを解放して再利用します(次のオブジェクト用)。

>>> for a in range(1,5): 
...  b = object() 
...  print b, id(b) 
... 
<object object at 0xb7db9470> 3084620912 
<object object at 0xb7db9468> 3084620904 
<object object at 0xb7db9470> 3084620912 
<object object at 0xb7db9468> 3084620904 
<object object at 0xb7db9470> 3084620912 

この場合、2つのメモリロケーションが再利用されています。あなたがリストに追加(または別の場所に保存)した場合、保存されます:

>>> a = [] 
>>> for b in range(1,5): 
...  c = object() 
...  a.append(c) 
...  print c, id(c) 
... 
<object object at 0xb7db9470> 3084620912 
<object object at 0xb7db9468> 3084620904 
<object object at 0xb7db9478> 3084620920 
<object object at 0xb7db9480> 3084620928 
3

Pythonドキュメントから:

IDを()オブジェクトの「アイデンティティ」を返し 。これは、そのオブジェクトの存続期間中に一意で定数であることが保証されている整数(または長整数)です。存続期間が重複しない2つのオブジェクトは、同じid()値を持つことがあります。

+0

これを掘り下げてくれてありがとう –

関連する問題