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 trialDominic Qu
3,435 PointsCreating an instance by calling a class?
The question is: Update hand in hands.py. I'm going to use code similar to Hand.roll(2) and I want to get back an instance of Hand with two D20's rolled in it. I should then be able to call Hand.total.
At first, I completed this task in a way that, when an instance is first made of the class, the instance will contain a list of D20 items and total will be able to be called. However, to my understanding, the task requires that the class be called, and an instance not be created beforehand. As such, I have attempted to implement a class method, which, to my understanding, is capable of allowing the user to call a class and an instance of the class to be returned, however I am unable to do so correctly. Help would be greatly appreciated
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, *args, **kwargs):
super().__init__(sides)
from dice import D20
class Hand(list):
def __init__(self,dice_list,*args, **kwargs):
super().__init__()
self = dice_list
@classmethod
def roll(cls,value):
hand = []
for _ in range(value):
hand.append(D20())
return cls(hand)
@property
def total(self):
return sum(self)
1 Answer
Steven Parker
231,248 PointsYou don't need to override "__init__" for this. Just remove that, and your "roll" class is good.
Dominic Qu
3,435 PointsDominic Qu
3,435 PointsThanks. How come that stops it from working?
Steven Parker
231,248 PointsSteven Parker
231,248 PointsThat code changed the "calling signature", requiring an argument to create an instance; so the validation mechanism encountered an error when trying to create an instance without one.
Happy coding!