Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

python - Typeerror: object.__new__() takes no parameters (help)

I'm simply trying to make a code that generates dice (in python). Here's the code:

import random

class Dice:
     def _init_(self, number_dice):
          self._dice = [6] * number_dice

     def roll_dice(self):
          for d in range(len(self._dice)):
               self._dice[d] = random.randit(1, 6)
          self._dice.sort()

     def print_roll(self):
          length = len(self._dice)
          print(str(lenth) + "dice:" + str(self._dice))



my_dice = Dice(2)
my_dice.roll_dice()
my_dice.print_roll()

The compiler says something about line 18. I'm new to programming so anything helps =]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need two underscores before and after __init__:

def __init__(self, number_dice):
    self._dice= [6] *number_dice

Otherwise, Python treats that method as a custom one and not the special __init__ constructor method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...