Search code examples
pythonconstructorclass-method

does the @classmethod work together with the __init__ method in python?


from dice import D20


class Hand(list):
    def __init__(self, size=0, die_class=D20, *args, **kwargs):
        super().__init__()
        for _ in range(size):
            self.append(die_class())

    @classmethod
    def roll(cls, size):
        return cls(size)

    @property
    def total(self):
        return sum(self)

If I use Hand.roll, is its size passed to Hand.__init__?


Solution

  • If you write Hand.roll(4), cls is Hand and the expression is exactly Hand(4). So the argument is passed to __init__ just as you’d expect.

    But one could write

    class Hand1(Hand):  # convenience for one die
      def __init__(self, d=6):
        super(Hand, self).__init__(1, dice.dN(d))
    

    and Hand1.roll(20) would pass d=20 to Hand1.__init__ instead. Whether this is a bug or a feature is up to you.