Idris AbdulwahabPro Student 2,902 Points
Please note that this is a follow up question. I made the argument for D20 generic in class Hand. And then I included it as an argument in the classmethod instance in roll. But i'm still not getting through. Please help to look it up. Regards.
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, size = 0, new_roll = None, *args, **kwargs): super().__init__() for _ in range(size): self.append(new_roll()) @classmethod def roll(cls, size): return cls(Hand(size, D20)) @property def total(self): return sum(self)
Schaffer Robichaux21,723 Points
I was able to catch up on what Steven Parker was describing to your earlier and I hope I can provide some help- but definitely not at the level Steven can.
I'll start with the mistakes I made that I recognize in your latest example as well - step by step:
class Hand(list): def __init__(self, size = 0, new_roll = None, *args, **kwargs): # 1. Why initialize more attributes here? super().__init__() # 2. If we are not overriding the init above , we don't need to call super(). to get list's methods for _ in range(size): # with 1. and 2. removed above, this logic is best suited inside a @classmethod self.append(new_roll())
@classmethod #3. This is required to make the method callable from 'Hand' def roll(cls, size): #4 What are the necessary arguments? return cls(Hand(size, D20))
- 1. As was previously pointed out, you don't need to override the init method. I initially did that as well and found that it can easily create conflicting attributes with ancestors further up the chain.
- 2. If you are not overriding the initialization, there is no need to call .super() in order to get the methods available in the list class
- 3. call the @classmethod
- As we did not override the init with additional parameters, we need to provide all the necessary arguments here. You are correct in providing cls, size but we can also provide an argument that holds our D20 class, cls, size=2, dice_type=D20
So at this point we have:
from dice import D20 class Hand(list): @classmethod def roll(cls, size=2, dice_type=D20): #declare a variable that holds an empty list #loop through the range of your size argument #append you dice_type() object to the list #return your variable with the newly appended list
I am sure there are more eloquent way of solving the problem; however, this is the route that made the most sense to me. Hope this help and please comment again if you continue to run into trouble