RecursionError:在其他类中创建类的对象时超出了最大递归深度

2024-09-27 23:15:51 发布

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

我想调用类中另一个类的对象,但当我运行代码时,它会显示:RecursionError:maximum recursion depth exceeded

有什么错误吗?在

这是我的代码:

class Anden(Estacion):

    def __init__ (self,ID):

        self.ID=ID
        self.filas_anden=[0,0,0,0,0,0,0,0,0,0]
        self.puertas = []

        while len(self.puertas) < 10:
            puerta = Puerta(len(self.puertas))


    def asignar_fila(self, pasajero):
        aux=10000000000
        puerta_asignada = min(filas_anden)

        for i in range(10):            
            if aux > self.puertas[i].total_fila:
                aux = self.puertas[i].total_fila
                fila_asignada = i
        pasajero.fila_actual = i 
        self.filas_anden[i] +=1
        self.puertas[i].append(pasajero)


class Puerta(Anden):

    def _init_ (self,ID):
        self.ID = ID
        self.lista_pasajeros = []
        self.total_fila = 0


    def ingresa_pasajero_fila(self, pasajero):
        self.lista_pasajeros.append(pasajero)
        self.total_fila = self.total_fila + 1

    def remover_pasajero_fila(self, pasajero):
        self.lista_pasajeros.remove(pasajero)
        self.total_fila = self.total_fila - 1

Tags: 代码selfiddefclasstotalauxlista
2条回答

所以有几件事。您在Puerta构造函数方法中出错。您使用的是_init_而不是__init__,因此当您初始化Puerta对象时,它将返回到其基类Anden的构造函数。这就是导致递归错误的原因。其次,在您的Anden构造函数方法中,我认为您要实现的目标是

def __init__ (self,ID):
    self.ID=ID
    self.filas_anden=[0,0,0,0,0,0,0,0,0,0]
    self.puertas = []

    while len(self.puertas) < 10:
        self.puertas.append(Puerta(len(self.puertas)))

在当前的实现中,只需将一个任意变量puerta设置为Puerta对象,该对象不会更改Anden实例的puertas列表,while循环将一直运行。希望这有帮助!在

您遇到了与Recursion error with class inheritance相同的问题。解决方案是使PuertaAnden通用的基类继承,而不是直接从Anden继承。在

相关问题 更多 >

    热门问题