Creating 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)
Steven Parker207,980 Points
You don't need to override "__init__" for this. Just remove that, and your "roll" class is good.