Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Python Class instances

Tags:

python

class

sum

I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rolled dice with different sides. Since a variable is passing the function instance what would be the best way to grab that value to add it up? Here is what I have.

*To clarify... I can get the totals of the roll1.roll_dice() to add up, but I have to show each roll individually and then the total of the three dice. I can do either one of those but not both.

class Die():

        def __init__(self, s = 6):
            self.sides = s
        def roll_die(self):
            x = random.randint(1,self.sides)
            return x

        roll1 = Die()   #Rolling die 1 with the default side of 6
        roll2 = Die(4)  #Rolling die 2 with 4 sides
        roll3 = Die(12) #Rolling die 3 with 12 sides

        print roll1.roll_die()  
        print roll2.roll_die()
        print roll3.roll_die()
like image 810
Jb. Avatar asked Dec 13 '25 20:12

Jb.


1 Answers

You can store the results in a list:

rolls = [Die(n).roll_die() for n in (6, 4, 12)]

then you can show the individual results

>>> print rolls
[5, 2, 6]

or sum them

>>> print sum(rolls)
13

Or, instead, you could keep a running total:

total = 0
for n in (6, 4, 12):
    value = Die(n).roll_die()
    print "Rolled a", value
    total += value
print "Total is", total

(edited to reflect the changes/clarifications to the question)

like image 60
dF. Avatar answered Dec 15 '25 09:12

dF.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!