TypeError:__ init __()至少需要2个参数(给定1个)错误

时间:2012-10-18 05:18:37

标签: python python-3.x

我正在使用Python3开发一个简单的基于文本的Dungeon游戏。首先,提示用户从screen.py文件中选择英雄。

from game import *


class GameScreen:
    '''Display the current state of a game in a text-based format.
    This class is fully implemented and needs no
    additional work from students.'''

    def initialize_game(self):
        '''(GameScreen) -> NoneType
        Initialize new game with new user-selected hero class
        and starting room files.'''

        hero = None
        while hero is None:
            c = input("Select hero type:\n(R)ogue (M)age (B)arbarian\n")
            c = c.lower()
            if c == 'r':
                hero = Rogue()
            elif c == 'm':
                hero = Mage()
            elif c == 'b':
                hero = Barbarian()

        self.game = Game("rooms/startroom", hero)

    def play(self):
        '''(Game) -> NoneType
        The main game loop.'''

        exit = False
        while not exit:
            print(self)
            if self.game.game_over():
                break
            c = input("Next: ")
            if c in ['q', 'x']:
                print("Thanks for playing!")
                exit = True
            elif c == 'w':  # UP
                self.game.move_hero(-1, 0)
            elif c == 's':  # DOWN
                self.game.move_hero(1, 0)
            elif c == 'a':  # LEFT
                self.game.move_hero(0, -1)
            elif c == 'd':  # RIGHT
                self.game.move_hero(0, 1)
            elif c == 'r':
                ## RESTART GAME
                self.initialize_game()
            else:
                pass

    def __str__(self):
        '''(GameScreen) -> NoneType
        Return a string representing the current room.
        Include the game's Hero string represetation and a
        status message from the last action taken.'''

        room = self.game.current_room
        s = ""

        if self.game.game_over():
            #render a GAME OVER screen with text mostly centered
            #in the space of the room in which the character died.

            #top row
            s += "X" * (2 + room.cols) + "\n"
            #empty rows above GAME OVER
            for i in list(range(floor((room.rows - 2) / 2))):
                s += "X" + " " * room.cols + "X\n"
            # GAME OVER rows
            s += ("X" + " " * floor((room.cols - 4) / 2) +
                "GAME" + " " * ceil((room.cols - 4) / 2) + "X\n")
            s += ("X" + " " * floor((room.cols - 4) / 2) +
                "OVER" + " " * ceil((room.cols - 4) / 2) + "X\n")
            #empty rows below GAME OVER
            for i in list(range(ceil((room.rows - 2) / 2))):
                s += "X" + " " * room.cols + "X\n"
            #bottom row
            s += "X" * (2 + room.cols) + "\n"
        else:
            for i in range(room.rows):
                for j in room.grid[i]:
                    if j is not None:
                        if j.visible:
                            s += j.symbol()
                        else:
                            #This is the symbol for 'not yet explored' : ?
                            s += "?"
                s += "\n"
        #hero representation
        s += str(self.game.hero)
        #last status message
        s += room.status
        return s

if __name__ == '__main__':
    gs = GameScreen()
    gs.initialize_game()
    gs.play()

每当我运行此代码时,我都会收到此错误:TypeError: init ()至少需要2个参数(给定1个),这与Rogue()或其他英雄类有关。这是hero.py。

class Rogue(Tile):
    '''A class representing the hero venturing into the dungeon.
    Heroes have the following attributes: a name, a list of items,
    hit points, strength, gold, and a viewing radius. Heroes
    inherit the visible boolean from Tile.'''

    def __init__(self, rogue, bonuses=(0, 0, 0)):
        '''(Rogue, str, list) -> NoneType
        Create a new hero with name Rogue,
        an empty list of items and bonuses to
        hp, strength, gold and radius as specified
        in bonuses'''

        self.rogue = rogue
        self.items = []
        self.hp = 10 + bonuses[0]
        self.strength = 2 + bonuses[1]
        self.radius = 2 + bonuses[2]
        Tile.__init__(self, True)

    def symbol(self):
        '''(Rogue) -> str
        Return the map representation symbol of Hero: O.'''

        #return "\u263b"
        return "O"

    def __str__(self):
        '''(Item) -> str
        Return the Hero's name.'''

        return "{}\nHP:{:2d} STR:{:2d} RAD:{:2d}\n".format(
                    self.rogue, self.hp, self.strength, self.radius)

    def take(self, item):
        '''ADD SIGNATURE HERE
        Add item to hero's items
        and update their stats as a result.'''

        # IMPLEMENT TAKE METHOD HERE
        pass

    def fight(self, baddie):
        '''ADD SIGNATURE HERE -> str
        Fight baddie and return the outcome of the
        battle in string format.'''

        # Baddie strikes first
        # Until one opponent is dead
            # attacker deals damage equal to their strength
            # attacker and defender alternate
        if self.hp < 0:
            return "Killed by"
        return "Defeated"

我做错了什么?

2 个答案:

答案 0 :(得分:9)

问题

GameScreen.initialize_game()中,您设置hero=Rogue(),但Rogue构造函数将rogue作为参数。 (换句话说,__init__的{​​{1}}要求传递Rogue。)设置roguehero=Mage时,您可能会遇到同样的问题。

解决方案

幸运的是,修复很简单;您只需将hero=Barbarian更改为hero=Rogue()即可。也许您可以在hero=Rogue("MyRogueName")中提示用户输入名称,然后使用该名称。

关于“至少2个参数(1个给定)”

的注释

当你看到这样的错误时,就意味着你调用了一个函数或一个方法而没有传递足够的参数。 (initialize_game只是在初始化对象时调用的特殊方法。)因此,在将来调试这样的东西时,请查看调用函数/方法的位置,以及定义它的位置,并确保这两个参数的数量相同。

对于这些类型的错误,有一点很棘手,就是传递的__init__

self

在这个例子中,有人可能会认为,“很奇怪,我已初始化>>> class MyClass: ... def __init__(self): ... self.foo = 'foo' ... >>> myObj = MyClass() ,因此myObj被调用了;为什么我不能传递MyClass.__init__的内容?”答案是只要使用“object.method()”表示法,就会有效地传入self。希望这有助于消除错误并解释如何在将来调试它。

答案 1 :(得分:1)

Class Rogue:
    ...
    def __init__(self, rogue, bonuses=(0, 0, 0)):
       ...
__init__类需要参数Rogue

rogue,但您要在hero = Rogue()中将其实例化为initialize_game

您需要将一些适当的参数传递给它,例如hero = Rogue('somename')