Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python Dice Roller RPG Roller

Eldin Guzin
Eldin Guzin
6,010 Points

RPG roller difficulty

It says that it cant get the length of the "Hand" , what does it mean by that ?

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
class Hand(list):

    @classmethod
    def roll(numrolls):
        for _ in range(numrolls):
            self.append(int(D20))
            return D20


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

2 Answers

Steven Parker
Steven Parker
229,670 Points

The funny error message just means that the definition of "Hand" has some issues. Here's some hints:

  • the D20 class needs to be imported from dice.py
  • this first argument of a class method should be the class itself (named "cls" by convention)
  • the loop should finish before "roll" returns
  • D20's should be added directly to the Hand (not converted to int)
  • a class name should be followed by parentheses when an instance is created
  • the "roll" should return a new "Hand" instance instead of a D20
Eldin Guzin
Eldin Guzin
6,010 Points

Can you explain what do you mean excatly by -the loop should finish before "roll" returns- how does that work, doesnt the number of rolls determine how many times is it suppose to be excecuted

''' from dice import D20

class Hand(list):

@classmethod
def roll(cls, numrolls):
    for _ in range(numrolls):
        self.append(Hand)
        return Hand


@property
def total(self):
    return sum(self)'''
Steven Parker
Steven Parker
229,670 Points

Yes, you're right about how many times the loop should repeat. But the "return" statement should come after the loop and not within it, because when it is inside the loop, the loop will only run one time.

The indentation level of the "return" statement determines if it is done inside or after the loop.

Also, remember that the method should return an instance of "Hand", not the class itself.