Calmcode - objects: classmethods

Classmethods in Python

1 2 3 4 5 6 7 8 9 10

Consider this new Dice definition.

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)

Given this new definition you can now create a new dice with the from_sides classmethod.

dice = Dice.from_sides(6)

Note the cls in the from_sides method instead of self. Technically, this is mostly a convention, not something that is demanded of you from the language. The cls is a variable that points to the class itself, not the object. Hence it is a convention to use cls instead of self in classmethods.