gpt4 book ai didi

Python:TypeError:__init__() 正好需要 2 个参数(给定 1 个)

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:02 25 4
gpt4 key购买 nike

我知道这个问题已经被问过好几次了,但没有人能为我提供解决方案。我读了这些:

__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)

我只是想让这些类(class)发挥作用。

最佳答案

您使用的代码如下:

player = Player()

这是一个问题,因为根据您的代码,__init__ 必须由一个名为 name 的参数提供。因此,要解决您的问题,只需为 Player 构造函数提供一个名称即可:

player = Player('sdfasf')

关于Python:TypeError:__init__() 正好需要 2 个参数(给定 1 个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30086384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com