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

Daniel Fragoso
Daniel Fragoso
5,333 Points

Can't pass this challenge for the life of me...

Can someone help me out here? Here's what I've got so far, I keep getting a "Can't get the length of a 'Hand'" error.

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__(20)
hands.py
from dice import Die, D20

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

    @classmethod
    def roll(cls, size):
        for _ in range(size):
            cls.append(D20)
        return cls

1 Answer

Steven Parker
Steven Parker
230,248 Points

I think you're pretty close.

This challenge gets a lot of questions, but it seems like most folks like to customize the intialization of Hand. I see you went for the same approach as I did, only adding the new code to roll (either method can be made to work).

But you have a few issues yet:

  • you probably don't want to append to the class itself (cls), create an instance first
  • when you roll (instantiate) the D20's, you need parentheses after the name
  • be sure to return the created instance
Daniel Fragoso
Daniel Fragoso
5,333 Points

This version of the code works in Workspaces but it doesn't pass the challenge. Can you help me out?

@classmethod
    def roll(self, sides):
        h=Hand()
        for _ in range(sides):
            h.append(D20().value)
        return h

Edit: I erased that .value and it worked! Thanks for the help!

Steven Parker
Steven Parker
230,248 Points

You don't need the value property, just "roll" the D20().

Otherwise it should work, even though a few things are a bit unconventional. Typically, the first argument of a classmethod would be named "cls", and normally you would refer to that instead of naming the class explicitly.