Python Acuses索引超出范围

问题描述

我从Python开始,直到进入课程部分为止,我一直表现不错。好吧,我正在尝试创建一个ChatBot,在主类中,函数Python pensar()返回iniciar,因此函数resp()可以将其附加到self.recente列表中。它按原样发生,但是当循环再次到达pensar()时,它不会获得self.recente [-1]。希望有人能帮助我。

这是课程代码:

class IA():
def __init__(self,nome):
    self.nome = nome
    self.recente = []

def ouvir(self):
    iniciar = input('»')
    iniciar = iniciar.upper()
    iniciar = iniciar.replace('O ','')
    return iniciar
    
    
def pensar(self,iniciar):
    if iniciar == 'OI':
        return 'Ola,qual seu nome?'
    if self.recente[-1] == 'Olá,qual seu nome?':
        a = self.pegar_nome()
        b = self.resp_nome(b)
    
        
def pegar_nome(self):
    pass
    
    
def resp_nome(self,iniciar):
    pass
    

def resp(self,iniciar):
    self.recente.append(iniciar)
    print(iniciar)

这是main.py之一:

    from Ia import IA

    tchau = ['TCHAU','XAU','ATE LOGO','ATÉ LOGO','ATE MAIS','ATÉ MAIS']
    
    while True:
        a = IA('Joao')
        b = a.ouvir()
        
        if b in tchau:
            print('Até mais')
            break
        
        c = a.pensar(b)
        a.resp(c)   

解决方法

问题的根本原因在于以下两个语句:

  1. self.recente[-1] --->试图获取不存在的数组元素。

  2. b = self.resp_nome(b) --->在初始化之前引用b。

可以通过以下步骤解决问题:

  1. 将语句转换为验证数组中是否存在特定值的条件。

    if 'Olá,qual seu nome?' not in self.recente:

  2. 将self.resp_nome(b)替换为self.resp_nome(a)

以下是实现了2个更改的工作示例:

# File name: python-class-demo.py

class IA():
    def __init__(self,nome):
        self.nome = nome
        self.recente = []

    def ouvir(self):
        iniciar = input('»')
        iniciar = iniciar.upper()
        iniciar = iniciar.replace('O ','')
        return iniciar
    
    
    def pensar(self,iniciar):
        if iniciar == 'OI':
            return 'Ola,qual seu nome?'
        if 'Olá,qual seu nome?' not in self.recente:
            a = self.pegar_nome()
            b = self.resp_nome(a)
    
        
    def pegar_nome(self):
        pass
    
    
    def resp_nome(self,iniciar):
        pass
    

    def resp(self,iniciar):
        self.recente.append(iniciar)
        print(iniciar)

tchau = ['TCHAU','XAU','ATE LOGO','ATÉ LOGO','ATE MAIS','ATÉ MAIS']

while True:
    a = IA('Joao')
    b = a.ouvir()
    
    if b in tchau:
        print('Até mais')
        break
    
    c = a.pensar(b)
    a.resp(c)

输出:

>python python-class-demo.py
»as
None
»OU
None
»TCHAU
Até mais
,

您可以在OOP中编写自变量:

>> (self.iniciar)

没有selfiniciar是全局变量

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...