Class method that appends a die as many times as the number in args
Task: In the hands.py file import the D20 class from dice.py. Create a classmethod named roll. It should take take the number of dice as an argument. Inside the roll classmethod create an empty list. Append a D20 to your list equal to the number of dice given as an argument to the roll classmethod. Then return the list of D20s. For example, if Hand.roll(2) is called, it would return a list with two D20s inside.
Question: My method takes a number of dice, creates a new list and iterates through the range of the number given as argument. For each iteration, the list appends a D20. What am I not seeing?
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)
from dice import D20 class Hand(list): @property def total(self): return sum(self) @class method def roll(number_of_dice): dicelist =  for i in range(1,number_of_dice): dicelist.append(D20) return dicelist
Steven Parker201,997 Points
There are a few issues:
- "@classmethod" should be one word
- the first parameter in a class method should be "cls"
- the internal list should be an instance of "Hand" (created using "cls")
- the range should start at 0 (or you can just omit the first argument)
- to create a new instance, "D20" must be followed by parentheses
@classmethod def roll(cls, number_of_dice): dicelist = cls() for i in range(number_of_dice): dicelist.append(D20()) return dicelist