-1

I made a class which looks like this:

import numpy.random as rand
class Dice:
    def __init__(self):
        self.x=0
    def roll(self):
        self.x=int(rand.randint(1,7,1))
        print(self.x)

Now, I want to roll two dices and make an array with the results.

A=Dice()
B=Dice()
aaa=[A.x, B.x]
print(aaa)

A.roll()
B.roll()
print(aaa)

The results look like:

[0, 0]
2
4
[0, 0]

What I wanted this code to act is to make the array update itself whenever the number inside changes. I know that I can make this with making another function, but is there any other ways to make this work more elegantly?

Sirius01
  • 3
  • 1
  • You cannot mutate an `int` object, but you can mutate your `Dice` objects. In other words, *the number inside the list never changes*. Keep your `Dice` objects in the list (not array) instead of `int` objects – juanpa.arrivillaga Aug 31 '20 at 11:41
  • 2
    as an aside, why on earth involve `numpy` in this? Just use `import random` – juanpa.arrivillaga Aug 31 '20 at 11:42
  • https://stackoverflow.com/questions/3402679/identifying-objects-why-does-the-returned-value-from-id-change – PYPL Aug 31 '20 at 11:47

2 Answers2

2

In your current code, the value in aaa is fixed once that line gets excuted. You should save the instances of Dice. And the repr method is used to pass info inside class out.

import numpy.random as rand
class Dice:
    def __init__(self):
        self.x=0
    def roll(self):
        self.x=int(rand.randint(1,7,1))
        print(self.x)
    def __repr__(self):
        return str(self.x)
A=Dice()
B=Dice()
aaa=[A, B]
print(aaa)

A.roll()
B.roll()
print(aaa)

Result:

[0, 0]
4
6
[4, 6]
lincr
  • 1,633
  • 1
  • 15
  • 36
0

you could keep track of your rolls in a list, and append new ones like this:

import numpy.random as rand
class Dice:
    def __init__(self):
        self.x=0
        self.dicelist = []
    def roll(self):
        self.x=int(rand.randint(1,7,1))
        self.dicelist.append(self.x)
        return self.dicelist
A=Dice()
A.roll()
A.roll()
A.roll()
print(A.roll())
#[3, 1, 4, 2]
barker
  • 1,005
  • 18
  • 36