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 trialRohan Tinna
3,415 PointsUnable to solve this code challenge
Code seems fine but not working
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)
from dice import D20
class Hand(list):
def __init__(self, num=2):
return Hand.roll(num)
@property
def total(self):
return sum(self)
@classmethod
def roll(cls, num):
hand = cls()
for _ in range(num):
hand.append(D20())
return hand
1 Answer
Anthony Grodowski
4,902 PointsI'm struggling with the same challange but I already see a couple of mistakes:
-
__init__()
can't return anything. - I'm not sure if
hand = cls()
is in this case proper. I think you should remove that line and just typereturn cls(hand)
at the end instead - You're ordered to return an instance, so in the
__init__
you should initialize an instance of what you've created in the classmethod.. - You're also ordered to create an instance, which contains the value of dices, so you need to create something that contains these values (in this case D20().value)
This is how I'm trying to do it but in a mysterious to me way cls(list_sum)
delets all the values from list_sum
and cls(list_sum)
is empty, unlike list_sum
alone:
from dice import D20
class Hand(list):
def __init__(self, list_sum=None):
self.list_sum = list_sum
@classmethod
def roll(cls, times):
list_sum = []
for _ in range(times):
list_sum.append(D20().value)
print(list_sum)
print(cls(list_sum))
return cls(list_sum)
@property
def total(self):
return sum(self)