Reputation: 31
I have created a class Dice where I have a function roll_die
that rolls a dice, and a function roll_dice
that rolls n number of dices. From this the program present the sum from the die or dices.
I have now tried to add a constructor that allows us to set number_of sides
to also be able to determine the number of sides on the die or dice, the sides can be 4,6,8,12 or 20, if it is not specified how many sides it should be automatically continued with a six-sided dice.
But I still get an error message TypeError: __init__() missing 1 required positional argument: 'sides'
when the number of pages is not specified, what did I do wrong?
class Dice:
def __init__(self, sides):
self.sides = sides
self.value = random.randint(1, self.sides)
def roll_die(self, sides):
return random.randint(1,sides)
def roll_dice(self,n):
sum = 0
for i in range(n):
sum += self.roll_die()
return sum
def number_of_dice(self, sides):
if sides == None:
sides = 6
elif sides not in (4,6,8,12,20):
print('The dice can only be of size 4,6,8,12 or 20')
Upvotes: 2
Views: 892
Reputation: 2428
I'd write your class like this
class Dice:
def __init__(self, sides=6):
if sides not in (4,6,8,12,20):
raise Exception("Invalid value for sides. Use one of following: 4, 6, 8, 12, 20")
self.sides = sides
def roll_dice(self):
return random.randint(1,self.sides)
def roll_dices(self, n):
sum = 0
for _ in range(n):
sum += self.roll_dice()
return sum
I didn't get what you used method number_of_dice
for, so I didn't add it. But that value check is included in constructor.
And I renamed method roll_die to roll_dice and method for rolling multiple times to roll_dices. It felt better.
Upvotes: 2
Reputation: 242
You should give it a default value in your constructor, which it will take when the argument is not supplied.
def __init__(self, sides=6):
self.sides = sides
self.value = random.randint(1, self.sides)
d = Dice(20) will return an instance of Dice with 20 sides d = Dice() will return an instance of Dice with 6 sides, which is the default.
Upvotes: 1