Calmcode - objects: methods

Methods in Python

1 2 3 4 5 6 7 8 9 10

Let's now add a method to our class so that we can actually simulate rolling it.

import random 

class Dice:
    def __init__(self, probs):
        self.probs = probs
    
    def roll(self, n=1):
        sides = list(self.probs.keys())
        probabilities = list(self.probs.values())
        return random.choices(sides, weights=probabilities, k=n)

If you've never seen this before it may look a bit strange. So let's go over a few things:

  • The .roll method accepts a self just like __init__ .
  • Because .roll receives self we can refer to the dictionary with all relevant dice values because these are attached to self.probs.
  • We use the random.choices function from the random module in Python to handle the simulation.

With this class definition we can create dice objects and start simulating!

dice = Dice({1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6})
dice.roll(n=10)