Python Object-Oriented Python Dice Roller RPG Roller

mourad marzouk
mourad marzouk
2,360 Points

How come this only works when I declare the die_class=D20 in the hand init?

I don't understand why this only works when I declare the die_class=D20 in the hand init,

rather then when Kenneth does it in a super of the YatzyHand in the previous video?

Is it because that's a separate class? or because in this case its a @classmethod? and if so can you please explain why? also for that matter why does the dice.py class D20 only work when I declare the sides=20 in the init rather then the super line after it? That is also what he does in the video. Yes I tried both.

dice.py
import random


class Die:
    def __init__(self, sides=2):
        if sides < 2:
            raise ValueError("Can't have fewer than two sides")
        self.sides = sides
        self.value = random.randint(1, sides)

    def __int__(self):
        return self.value

    def __add__(self, other):
        return int(self) + other

    def __radd__(self, other):
        return self + other

class D20(Die):
    def __init__(self, sides=20):
        super().__init__(sides)
hands.py
from dice import D20

class Hand(list):

    def __init__(self, size=0, die_class=D20):
        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)

1 Answer

Dave StSomeWhere
Dave StSomeWhere
19,208 Points

Looks like you have 2 questions.

  1. I don't understand why this only works when I declare the die_class=D20 in the hand init, Because you didn't test it properly (haha, just kidding) You could just hard code D20() into the self.append(), but since you are using an input parameter, then that needs to be defined.

  2. why does the dice.py class D20 only work when I declare the sides=20 in the init rather then the super line after it? not sure what isn't working for you but it does work defining the sides on the super().__init__(), the key is getting the default value in there.

Try using the following snippets - they should work just fine:

class D20(Die):
    def __init__(self):
        super().__init__(sides=20)


class Hand(list):
    def __init__(self, size=0):
        super().__init__()

        for _ in range(size):
            self.append(D20())

Does that help answer your questions?

mourad marzouk
mourad marzouk
2,360 Points

Oh interesting, didn't realize you can write it like that as well. I like that much better and looks cleaner. but I think I understand what your saying and that it's because the dice class used why laid out differently so had to match it right?