我知道这个问题已经问过好几次了,但没有人能给我提供解决问题的办法。我读到这些:
__init__() takes exactly 2 arguments (1 given)?
class __init__() takes exactly 2 arguments (1 given)
我所要做的就是为一个“生存游戏”创建两个类,就像一个非常糟糕的minecraft版本。下面是这两个类的完整代码:
class Player:
'''
Actions directly relating to the player/character.
'''
def __init__(self, name):
self.name = name
self.health = 10
self.shelter = False
def eat(self, food):
self.food = Food
if (food == 'apple'):
Food().apple()
elif (food == 'pork'):
Food().pork()
elif (food == 'beef'):
Food().beef()
elif (food == 'stew'):
Food().stew()
class Food:
'''
Available foods and their properties.
'''
player = Player()
def __init__(self):
useless = 1
Amount.apple = 0
Amount.pork = 0
Amount.beef = 0
Amount.stew = 0
class Amount:
def apple(self):
player.health += 10
def pork(self):
player.health += 20
def beef(self):
player.health += 30
def stew(self):
player.health += 25
现在对于完整的错误:
Traceback (most recent call last):
File "/home/promitheas/Desktop/programming/python/pygame/Survive/survive_classe s.py", line 26, in <module>
class Food:
File "/home/promitheas/Desktop/programming/python/pygame/Survive/survive_classe s.py", line 30, in Food
player = Player()
TypeError: __init__() takes exactly 2 arguments (1 given)
我只想让这些课程发挥作用。
您使用的代码如下:
这是一个问题,因为根据您的代码,
__init__
必须由一个名为name
的参数提供。因此,要解决您的问题,只需为Player构造函数提供一个名称,就可以设置:问题是类
Player
的__init__
函数在初始化类实例时接受name
参数。第一个参数self
在创建类实例时自动处理。所以你必须改变到
启动并运行程序。
__init__()
是类实例化时调用的函数。因此,创建实例时需要传递__init__
所需的任何参数。所以,代替使用
第一个参数是隐式}是必需的。你得到错误是因为你没有包括它。
self
,在实例化时不需要包含它。^但是{相关问题 更多 >
编程相关推荐