Python:TypeError:\uuu init\uuu()只接受2个参数(给定1个)

2024-06-16 09:11:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这个问题已经问过好几次了,但没有人能给我提供解决问题的办法。我读到这些:

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

我只想让这些课程发挥作用。


Tags: selfapplefoodinitdefamountclassplayer
3条回答

您使用的代码如下:

player = Player()

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

player = Player('sdfasf')

问题是类Player__init__函数在初始化类实例时接受name参数。第一个参数self在创建类实例时自动处理。所以你必须改变

player = Player()

player = Player('somename')

启动并运行程序。

__init__()是类实例化时调用的函数。因此,创建实例时需要传递__init__所需的任何参数。所以,代替

player = Player()

使用

player = Player("George")

第一个参数是隐式self,在实例化时不需要包含它。^但是{}是必需的。你得到错误是因为你没有包括它。

相关问题 更多 >