why is python reusing a class instance inside in function

2024/7/2 14:57:22

I'm running a for loop inside a function which is creating instances of a class to test them. instead of making new classes it appears to be reusing the same two over and over.

Is there something I'm missing about how classes and variables are handled in python methods?

how can I generate a new object for each iteration of the loop

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.imagesprint('colleciton: %s id: %s' % (collection,id(collection)))self.assertEqual(images_by_keyword, class_images,)

here is the output

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

when I use seperate variable names I get seperate ids for each instance as expected:

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)))

outputs:

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
Answer

All that shows is that the memory of the objects is being reused, not that new objects aren't being instantiated. In each iteration collection is being overwritten, hence the previous object's reference count drops and the Python interpreter is free to deallocate its memory and reuse it (for the next object).

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

In this case, 2 memory locations are being reused. If you were to add it to a list (or save it elsewhere), it would be preserved:

>>> 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
https://en.xdnf.cn/q/73257.html

Related Q&A

How to set locale in Altair?

Im successfully creating and rendering a chart in Altair with a currency prefix ($), but I need this to be set to GBP (£). I know that theres a Vega-lite formatLocale which can be set, but I cant …

Show/hide a plots legend

Im relatively new to python and am developing a pyqt GUI. I want to provide a checkbox option to show/hide a plots legend. Is there a way to hide a legend? Ive tried using pyplots _nolegend_ and it ap…

Difference between iterating over a file-like and calling readline

I always thought iterating over a file-like in Python would be equivalent to calling its readline method in a loop, but today I found a situation where that is not true. Specifically, I have a Popend p…

Creating `input_fn` from iterator

Most tutorials focus on the case where the entire training dataset fits into memory. However, I have an iterator which acts as an infinite stream of (features, labels)-tuples (creating them cheaply on …

A Python one liner? if x in y, do x

numbers = [1,2,3,4,5,6,7,8,9] number = 1Can I write the following on one line?if number in numbers:print numberUsing the style of ruby:puts number if numbers.include?(number)I have tried:print number…

Adjusting the ticks to fit within the figure

I have the following matplotlib code which all it does is plots 0-20 on the x-axis vs 0-100 on the y-axisimport matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.plot(range(20)) …

Python ctypes: pass argument by reference error

I have a C++ function that I want you call in Python 2.7.12, looking like this:extern "C" {double* myfunction(double* &y, double* &z, int &n_y, int &n_z, int a, int b){vector&…

Python: Print next x lines from text file when hitting string

The situation is as follows:I have a .txt file with results of several nslookups.I want to loop tru the file and everytime it hits the string "Non-authoritative answer:" the scripts has to pr…

Writing to a Google Document With Python

I have some data that I want to write to a simple multi-column table in Google Docs. Is this way too cumbersome to even begin attempting? I would just render it in XHTML, but my client has a very spec…

Numpy/ Pandas/ Matplotlib taking too long to install

Ive decided to install of MacOs Big Sur and now I do have to reinstall all the packages again... But Im facing some problems. I dont have much experience using terminal, but it is taking too long to in…