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,935 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.