TypeError: __init__() prend au moins 2 arguments (1 donnée) erreur
Je suis en train d'élaborer un texte simple en fonction du Donjon jeu à l'aide de Python3. D'abord, l'utilisateur est invité à sélectionner le héros de screen.py fichier.
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()
Chaque fois que j'exécute ce code, j'obtiens cette erreur: TypeError: init() prend au moins 2 arguments (1) qui a à voir avec Rogue() ou d'autres classes de héros. Voici l'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"
Ce que je fais mal?
OriginalL'auteur sachitad | 2012-10-18
Vous devez vous connecter pour publier un commentaire.
Le Problème
Dans
GameScreen.initialize_game()
, vous définissezhero=Rogue()
, mais leRogue
constructeur prendrogue
comme argument. (Autrement dit, le__init__
deRogue
exige querogue
être adopté.) Vous avez probablement ce problème lorsque vous définissezhero=Mage
ethero=Barbarian
.La Solution
Heureusement, la solution est simple, il vous suffit de modifier
hero=Rogue()
àhero=Rogue("MyRogueName")
. Vous pourriez peut-être demander à l'utilisateur un nom dansinitialize_game
, et ensuite utiliser ce nom.Notes sur "au moins 2 arguments (1 donnée)"
Quand vous voyez des erreurs de ce type, cela signifie que vous avez appelé une fonction ou d'une méthode sans passer assez d'arguments pour elle. (
__init__
est juste une méthode spéciale qui est appelée lorsqu'un objet est initialisé.) Ainsi, lorsque le débogage des trucs de ce genre dans l'avenir, de regarder où vous appelez une fonction/méthode, et où vous définissez et assurez-vous que les deux ont le même nombre de paramètres.Une chose qui est une sorte de délicat sujet de ces types d'erreurs, est le
self
qui passe autour.Dans cet exemple, l'on pourrait penser, "Bizarre, j'ai initialisé
myObj
, doncMyClass.__init__
a été appelé; pourquoi n'ai-je pas passer à quelque chose pourself
?" La réponse est queself
est effectivement passé à chaque fois que l'objet".méthode()" notation est utilisée. J'espère que ça aide à faire disparaître l'erreur et explique comment le corriger dans l'avenir.Oui, je reçois le même message d'erreur dans Mage et Barbare. Maintenant, chaque fois que je passe argument tout en appelant Voyous ("Bonjour"), j'obtiens cette erreur "TypeError: __init__() prend exactement 2 arguments de position (3)"
oh Désolé j'ai fait une erreur. Il fonctionne très bien maintenant. Merci beaucoup pour la bonne explication. J'ai bien compris l'orienté-objet, concept et l'utilisation du premier paramètre "auto".
Par curiosité, quelle est l'erreur? J'ai essayé dur de trouver une raison pour laquelle vous pourriez obtenir cette erreur, haha. Aussi, content que cela a aidé.
Ce code dans "l'auto.jeu = Jeu("chambres/startroom", héros)" attend argument héros dans le Jeu de la classe dont j'ai oublié de mentionner dans le Jeu réel de la classe. Merci
OriginalL'auteur Matthew Adams
__init__
de votreRogue
les besoins de la classe paramètrerogue
, mais vous êtes l'instanciation commehero = Rogue()
dansinitialize_game
.Vous avez besoin pour passer un paramètre comme
hero = Rogue('somename')
OriginalL'auteur Rohan