Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Brad Givens6,621 Points
RPG challenge 2/2. Hands.total not correct value
Keep getting error saying the total value is not correct but I don't see anything that is jumping out at me for being incorrect.
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)
from dice import D20 class Hand(list): def __init__(self, dice, *args, **kwargs): super().__init__(dice) @classmethod def roll(cls, num): result =  for _ in range(num): result.append(D20()) return cls(result) @property def total(self): return sum(self)
Jay ReyesPython Web Development Techdegree Student 15,937 Points
The thing is we don't need to override
__init__ -- at least for now.
It turns out, in the scope of the classmethod, we can call
cls() (which Kenneth glosses over, I think). Based on this article,
cls() will construct class
Hand and call the
So the only piece of code you need to add is:
@classmethod def roll(cls, size=0, die_type=D20): hand = cls() for _ in range(size): hand.append(die_type()) return hand
The below are just my thoughts:
From a high level view, class methods are another way to run the class
__init__. I'll now view class methods as template (or constructor).
So it makes sense to name the object
hand because we are "stuffing" the class (as an "instance"...) into the class method as a list.
Now, the difference between an instance (not instance method) and a class method? Maybe an instance is the default template while class method is an alternative template.