我在运行以下代码时遇到错误:
class Person:
def _init_(self, name):
self.name = name
def hello(self):
print 'Initialising the object with its name ', self.name
p = Person('Constructor')
p.hello()
Run Code Online (Sandbox Code Playgroud)
输出是:
Traceback (most recent call last):
File "./class_init.py", line 11, in <module>
p = Person('Harry')
TypeError: this constructor takes no arguments
Run Code Online (Sandbox Code Playgroud)
有什么问题?
如果您的问题作为此问题的重复项而被关闭,那是因为您有一个代码示例,其中包含以下任一内容:
class Example:
def __int__(self, parameter):
self.attribute = parameter
Run Code Online (Sandbox Code Playgroud)
或者:
class Example:
def _init_(self, parameter):
self.attribute = parameter
Run Code Online (Sandbox Code Playgroud)
当您随后尝试创建该类的实例时,会发生错误:
>>> Example("an argument")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Example() takes no arguments
Run Code Online (Sandbox Code Playgroud)
(在某些版本的 Python 中,错误可能会显示TypeError: object.__new__() takes no parameters。)
或者,该类的实例似乎缺少属性:
>>> class Example:
... def __int__(self): # or _init_
... self.attribute = 'value'
>>> Example().attribute
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Example' object has no …Run Code Online (Sandbox Code Playgroud) 我只是想制作一个生成骰子的代码(在python中).这是代码:
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()
Run Code Online (Sandbox Code Playgroud)
编译器对第18行说了些什么.我是编程的新手,所以任何事情都有帮助=]