Take the following example:
from pprint import pprint
class ResultsClass:
def __init__(self,
name = None,
counts = []):
self.name = name
self.counts = counts
objs = [ResultsClass() for i in range(5)]
i = 0
while i < 4:
objs[i].counts.append("count is " + str(i))
pprint(objs[i].counts)
i = i+1
The results are:
['count is 0']
['count is 0', 'count is 1']
['count is 0', 'count is 1', 'count is 2']
['count is 0', 'count is 1', 'count is 2', 'count is 3']
I have also tried the following code to no avail:
i = 0
objs = [ResultsClass() for i in range(5)]
for obj in objs:
obj.counts.append("count is " + str(i))
pprint(obj.counts)
i = +1
What I want to do is have each instance of ResultsClass with a different counts list, like so:
['count is 0']
['count is 1']
['count is 2']
['count is 3']
Coming from a PowerShell background, I would have thought Python would iterate through each instance of the object and append to that specific list therein; instead it seems to be appending to the list of objects and all instances of the counts property.
What's the best way of achieving the desired result?