Let's add another dunder method to the class.
import random
class Dice:
def __init__(self, probs):
self.probs = probs
self.expected_value = sum(i * p for i, p in self.probs.items())
@classmethod
def from_sides(cls, n=6):
return cls({i: 1/n for i in range(1, n + 1)})
def roll(self, n=1):
sides = list(self.probs.keys())
probabilities = list(self.probs.values())
return random.choices(sides, weights=probabilities, k=n)
def __len__(self):
return len(self.probs)
The __len__
dunder method returns the number of sides of the dice and it allows you to use the generic len()
function on the object.
dice = Dice({1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6})
len(dice)
It might feel like a modest feature, but there's lots to appreciate here. Because Python carries a len()
function that is generic we can have one single way of getting a length on any Python object. This is really pragmatic!