Python Object-Oriented Python Dice Roller RPG Roller

Dominic Qu
Dominic Qu
3,160 Points

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

dice.py
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)
hands.py
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
Steven Parker
202,104 Points

You don't need to override "__init__" for this. Just remove that, and your "roll" class is good. :+1:

Dominic Qu
Dominic Qu
3,160 Points

Thanks. How come that stops it from working?

Steven Parker
Steven Parker
202,104 Points

That 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!