Python Object-Oriented Python Dice Roller RPG Roller

I could not find out how to solve this task.

I tried to add some methods and I do not understand how I can solve this problem.

Challenge is: https://teamtreehouse.com/library/objectoriented-python-2/dice-roller/rpg-roller

                                                      Challenge Task 2 of 2

Now update Hand in hands.py. I'm going to use code similar to Hand.roll(2) and I want to get back an instance of Hand with two D20s rolled in it. I should then be able to call .total on the instance to get the total of the two dice.

I'll leave the implementation of all of that up to you. I don't care how you do it, I only care that it works.

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):
        super().__init__(sides=20)
hands.py
from dice import D20

class Hand(list):
    @property
    def total(self):
        return sum(self)

    def __init__(self):
        self.dies = []

    @classmethod
    def roll(size):
      print(size)
      hand_with_two_d20 = Hand()

      for _ in range(size):
        hand_with_two_d20.dies.append(D20())

      return hand_with_two_d20

    def __len__(self):
        return len(self.dies)

print(Hand.roll(2))

When I run the code, I am getting the error message below:

Traceback (most recent call last): File "hands.py", line 24, in <module> print(Hand.roll(2)) TypeError: roll() takes 1 positional argument but 2 were given 

2 Answers

Steven Parker
Steven Parker
202,109 Points

The system provides the first parameter to a method, and for a class method it will be a reference to the class itself. By convention the parameter name given for this is "cls". You can call it from inside the method to create a new instance.

"Hand" should not have a "dies" attribute. It is a type of list, so you can append items directly to an instance.

And this method doesn't need to "print" anything.

Thank you!