0

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.

aaa
  • 196
  • 8
  • You could simply just ```self.results.clear()``` after ```self.results=results``` –  Jun 26 '21 at 09:36

1 Answers1

1

That is because you use a mutable object as defaut parameter value, results=[], the same list is used for each instance, change to

def __init__(self, results=None, nsides=6):
    self.results = results or []
    self.nsides = nsides
azro
  • 53,056
  • 7
  • 34
  • 70