When I create three instances of this dice class and call the roll function, I expect to get three separate lists of rolls with 2 rolls in each, that is, one unique list per instance x, y
and z
. Instead, every time I roll for a new dice I get the results from the other instances plus the new rolls... What am I doing wrong?
from random import randint
class Dice:
def __init__(self, results = [], nsides = 6):
self.results = results
self.nsides = nsides
def roll(self, n):
for i in range(n):
self.results.append(randint(1, self.nsides))
return(self.results)
x = Dice()
x.roll(2)
print(x.results)
y = Dice()
y.roll(2)
print(y.results)
z = Dice()
z.roll(2)
print(z.results)
Output:
[4, 6]
[4, 6, 5, 1]
[4, 6, 5, 1, 4, 3]
Expected:
[4, 6]
[5, 1]
[4, 3]
Note that the current output is the correct expected output if I would have ran x.roll(2)
three times.