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

标签 python class typeerror

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

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

相关文章:

python - 如何使用Multiindex聚合到pandas列表中?

python - 情感分类中的缺失值

objective-c - 包含文件时出错

haskell - 如何解决这个 Haskell 类型错误?预期类型和实际类型不匹配

apache-spark - 使用 lit() 在 Spark 中创建新列

Python - 如何查找多维数组中是否存在某个项目?

java - 我的成员变量在 Eclipse 中用红色下划线表示

java - 如何在 Java 中使用 for 循环从类创建新对象?

python - 继续获取,类型错误 : a float is required

python - scikit-learn 中带有 LeaveOneOut 的 roc_auc 评分方法