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 trialTefileo Stephens
2,295 PointsHi There, I'm stuck on the RPG roller challenge Task 2 of 2. Does anybody have the answer?
My code works when I use Pycharm on my computer but doesn't pass the online check, does anybody know why?
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):
def __init__(self):
super().__init__()
def roll(self, NumberOfRolls):
for rolls in range(NumberOfRolls):
self.append(int(D20()))
@property
def total(self):
return sum(self)
Hand = Hand()
2 Answers
Steven Parker
231,236 PointsHere's a few hints:
- since the method will be called directly on the class, it won't have a "self"
- you might want to implement "roll" as a class method
- the "roll" method above returns nothing, but it is expected to return a new instance
- it's not necessary to override "
__init__
"
Tefileo Stephens
2,295 PointsGood answer, thanks!
Ash Isbitt
3,473 PointsAsh Isbitt
3,473 PointsHi Steven - can you explain why in this task the "Roll" method should be a class method?
Steven Parker
231,236 PointsSteven Parker
231,236 PointsThe challenge showed an example of how the method would be called directly on "Hand" (the class itself) instead of on an instance. So for that to work, it needs to be a class method.