Python Object-Oriented Python Dice Roller RPG Roller

Creating an instance by calling a class?

The question is: Update hand in 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

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):
from dice import D20

class Hand(list):
    def __init__(self,dice_list,*args, **kwargs):
        self = dice_list

    def roll(cls,value):
        hand = []
        for _ in range(value):
        return cls(hand)

    def total(self):
        return sum(self)

1 Answer

Steven Parker
Steven Parker
207,980 Points

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

Thanks. How come that stops it from working?

Steven Parker
Steven Parker
207,980 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!