首页 > 解决方案 > Python / TypeError:无法解压不可迭代的 Jugador 对象

问题描述

嘿伙计们,我试图在 for 循环中创建 N 个对象,但它给了我一个错误TypeError: cannot unpack non-iterable Jugador object

你能帮我吗?

我做错了什么?

这是我的代码:


from Jugador import Jugador
class Juego():
    tipoJuego = ""
    nJugadores = ""


    def __init__(self,tipoJuego, nJugadores):
        self.tipoJuego = tipoJuego
        self.nJugadores = nJugadores
        nJugadoresInt = int(nJugadores)
        tipoJuegoInt = int(tipoJuego)


        if tipoJuegoInt == 1 or tipoJuegoInt == 2 or tipoJuegoInt == 3:
            print("Has elegido el tipo de juego ",tipoJuegoInt, ", y van a jugar ", nJugadores, " Personas")
        else:
            print("Error: Tipo de juego invalido")
            exit()


        for i in range(1,nJugadoresInt):
            print("Jugador",i, "introduzca el nombre de usuario:")
            nUsu = input()

            print("Introduzca la edad:")
            age = input()

            print("Introduzca la palabra elegida:")
            word = input()

            J,i = Jugador(nUsu, age, word)

标签: python

解决方案


如果您打算创建一种方法来分配 N 个对象以便稍后找到它们,我可以建议将它们存储在一个列表中J

from Jugador import Jugador
class Juego():
    tipoJuego = ""
    nJugadores = ""


    def __init__(self,tipoJuego, nJugadores):
        self.tipoJuego = tipoJuego
        self.nJugadores = nJugadores
        nJugadoresInt = int(nJugadores)
        tipoJuegoInt = int(tipoJuego)


        if tipoJuegoInt == 1 or tipoJuegoInt == 2 or tipoJuegoInt == 3:
            print("Has elegido el tipo de juego ",tipoJuegoInt, ", y van a jugar ", nJugadores, " Personas")
        else:
            print("Error: Tipo de juego invalido")
            exit()

        J = []
        for i in range(1,nJugadoresInt):
            print("Jugador",i, "introduzca el nombre de usuario:")
            nUsu = input()

            print("Introduzca la edad:")
            age = input()

            print("Introduzca la palabra elegida:")
            word = input()

            J.insert(i,Jugador(nUsu, age, word))

供参考:https ://docs.python.org/3.8/tutorial/datastructures.html


推荐阅读