TypeError: __init__() takes at least 2 arguments (1 given) error

后端 未结 2 548
自闭症患者
自闭症患者 2020-12-19 05:48

I am developing a simple text based Dungeon game using Python3. First the user is prompted to select the hero from screen.py file.

from game import *


class         


        
相关标签:
2条回答
  • 2020-12-19 05:56
    Class Rogue:
        ...
        def __init__(self, rogue, bonuses=(0, 0, 0)):
           ...
    

    __init__ of your Rogue class needs parameter rogue, but you are instantiating it as hero = Rogue() in initialize_game.

    You need to pass some appropriate parameter to it like hero = Rogue('somename')

    0 讨论(0)
  • 2020-12-19 06:05

    The Problem

    In GameScreen.initialize_game(), you set hero=Rogue(), but the Rogue constructor takes rogue as an argument. (Said another way, the __init__ of Rogue requires that rogue be passed in.) You likely have this same issue when you set hero=Mage and hero=Barbarian.

    The Solution

    Luckily the fix is simple; you can just change hero=Rogue() to hero=Rogue("MyRogueName"). Maybe you could prompt the user for a name in initialize_game, and then use that name.

    Notes on "at least 2 arguments (1 given)"

    When you see errors like this, it means that you have called a function or a method without passing enough arguments to it. (__init__ is just a special method that is called when an object is initialized.) So when debugging stuff like this in the future, look at where you call a function/method, and where you define it, and make sure that the two have the same number of parameters.

    One thing that is sort of tricky about these kinds of errors, is the self that gets passed around.

    >>> class MyClass:
    ...     def __init__(self):
    ...             self.foo = 'foo'
    ... 
    >>> myObj = MyClass()
    

    In that example, one might think, "Weird, I initialized myObj, so MyClass.__init__ was called; why didn't I have to pass in something for self?" The answer is that self is effectively passed in whenever the "object.method()" notation is used. Hopefully that helps clear up the error and explains how to debug it in the future.

    0 讨论(0)
提交回复
热议问题